Skip to main content
summaryrefslogtreecommitdiffstats
blob: d12ae09308747bf60730185619ffe3cee9bb93ee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*******************************************************************************
 * Copyright (c) 2000, 2003 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.team.internal.core.subscribers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.MultiRule;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.core.Assert;
import org.eclipse.team.internal.core.Policy;
import org.eclipse.team.internal.core.TeamPlugin;

/**
 * Provides a per-thread nested locking mechanism. A thread can acquire a
 * lock on a specific resource by calling acquire(). Subsequently, acquire() can be called
 * multiple times on the resource or any of its children from within the same thread
 * without blocking. Other threads that try
 * and acquire the lock on those same resources will be blocked until the first 
 * thread releases all it's nested locks.
 * <p>
 * The locking is managed by the platform via scheduling rules. This class simply 
 * provides the nesting mechnism in order to allow the client to determine when
 * the lock for the thread has been released. Therefore, this lock will block if
 * another thread already locks the same resource.</p>
 */
public class BatchingLock {

	private final static boolean DEBUG = false;
	
	// This is a placeholder rule used to indicate that no scheduling rule is needed
	/* internal use only */ static final ISchedulingRule NULL_SCHEDULING_RULE= new ISchedulingRule() {
		public boolean contains(ISchedulingRule rule) {
			return false;
		}
		public boolean isConflicting(ISchedulingRule rule) {
			return false;
		}
	};
	
	public class ThreadInfo {
		private Set changedResources = new HashSet();
		private IFlushOperation operation;
		private List rules = new ArrayList();
		public ThreadInfo(IFlushOperation operation) {
			this.operation = operation;
		}
		/**
		 * Push a scheduling rule onto the stack for this thread and
		 * acquire the rule if it is not the workspace root.
		 * @param resource
		 */
		public ISchedulingRule pushRule(ISchedulingRule resource, IProgressMonitor monitor) {
			// The scheduling rule is either the project or the resource's parent
			ISchedulingRule rule = getRuleForResoure(resource);
			if (rule != NULL_SCHEDULING_RULE) {
				try {
					Platform.getJobManager().beginRule(rule, monitor);
				} catch (OperationCanceledException e) {
					// The begin was cancelled.
					// Free the scheduling rule and throw the cancel
					// so the clients of ReentrantLock don't need to
					// do an endRule when the operation is cancelled.
					Platform.getJobManager().endRule(rule);
					throw e;
				}
			}
			addRule(rule);
			return rule;
		}
		/**
		 * Pop the scheduling rule from the stack and release it if it
		 * is not the workspace root. Flush any changed sync info to 
		 * disk if necessary. A flush is necessary if the stack is empty
		 * or if the top-most non-null scheduling rule was popped as a result
		 * of this operation.
		 * @param monitor
		 * @throws CVSException
		 */
		public void popRule(ISchedulingRule rule, IProgressMonitor monitor) throws TeamException {
			try {
				if (isFlushRequired()) {
					flush(monitor);
				}
			} finally {
				ISchedulingRule stackedRule = removeRule();
				if (rule == null) {
					rule = NULL_SCHEDULING_RULE;
				}
				Assert.isTrue(stackedRule.equals(rule), "end for resource '" + rule + "' does not match stacked rule '" + stackedRule + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
				if (rule != NULL_SCHEDULING_RULE) {
					Platform.getJobManager().endRule(rule);
				}
			}
		}
		private ISchedulingRule getRuleForResoure(ISchedulingRule resourceRule) {
			ISchedulingRule rule;
			if (resourceRule instanceof IResource) {
				IResource resource = (IResource)resourceRule;
				if (resource.getType() == IResource.ROOT) {
					// Never lock the whole workspace
					rule = NULL_SCHEDULING_RULE;
				} else  if (resource.getType() == IResource.PROJECT) {
					rule = resource;
				} else {
					rule = resource.getParent();
				}
			} else if (resourceRule instanceof MultiRule) {
				// Create a MultiRule for all projects from the given rule
				ISchedulingRule[] rules = ((MultiRule)resourceRule).getChildren();
				Set projects = new HashSet();
				for (int i = 0; i < rules.length; i++) {
					ISchedulingRule childRule = rules[i];
					if (childRule instanceof IResource) {
						projects.add(((IResource)childRule).getProject());
					}
				}
				if (projects.isEmpty()) {
					rule = NULL_SCHEDULING_RULE;
				} else if (projects.size() == 1) {
					rule = (ISchedulingRule)projects.iterator().next();
				} else {
					rule = new MultiRule((ISchedulingRule[]) projects.toArray(new ISchedulingRule[projects.size()]));
				}
			} else {
				// Rule is not associated with resources so ignore it
				rule = NULL_SCHEDULING_RULE;
			}
			return rule;
		}
		/**
		 * Return <code>true</code> if we are still nested in
		 * an acquire for this thread.
		 * 
		 * @return
		 */
		public boolean isNested() {
			return !rules.isEmpty();
		}
		public void addChangedResource(IResource resource) {
			changedResources.add(resource);
		}
		public boolean isEmpty() {
			return changedResources.isEmpty();
		}
		public IResource[] getChangedResources() {
			return (IResource[]) changedResources.toArray(new IResource[changedResources.size()]);
		}
		public void flush(IProgressMonitor monitor) throws TeamException {
			try {
				operation.flush(this, monitor);
			} catch (OutOfMemoryError e) {
				throw e;
			} catch (Error e) {
				handleAbortedFlush(e);
				throw e;
			} catch (RuntimeException e) {
				handleAbortedFlush(e);
				throw e;
			}
			changedResources.clear();
		}
		private boolean isFlushRequired() {
			return rules.size() == 1 || remainingRulesAreNull();
		}
		/*
		 * Return true if all but the last rule in the stack is null
		 */
		private boolean remainingRulesAreNull() {
			for (int i = 0; i < rules.size() - 1; i++) {
				ISchedulingRule rule = (ISchedulingRule) rules.get(i);
				if (rule != NULL_SCHEDULING_RULE) {
					return false;
				}
			}
			return true;
		}
		private void handleAbortedFlush(Throwable t) {
			TeamPlugin.log(IStatus.ERROR, Policy.bind("BatchingLock.11"), t); //$NON-NLS-1$
		}
		private void addRule(ISchedulingRule rule) {
			rules.add(rule);
		}
		private ISchedulingRule removeRule() {
			return (ISchedulingRule)rules.remove(rules.size() - 1);
		}
		public boolean ruleContains(IResource resource) {
			for (Iterator iter = rules.iterator(); iter.hasNext();) {
				ISchedulingRule rule = (ISchedulingRule) iter.next();
				if (rule != NULL_SCHEDULING_RULE && rule.contains(resource)) {
					return true;
				}
			}
			return false;
		}
	}
	
	public interface IFlushOperation {
		public void flush(ThreadInfo info, IProgressMonitor monitor) throws TeamException;
	}
	
	private Map infos = new HashMap();
	
	private ThreadInfo getThreadInfo() {
		Thread thisThread = Thread.currentThread();
		synchronized (infos) {
			ThreadInfo info = (ThreadInfo)infos.get(thisThread);
			return info;
		}
	}
	
	private ThreadInfo getThreadInfo(IResource resource) {
		synchronized (infos) {
			for (Iterator iter = infos.values().iterator(); iter.hasNext();) {
				ThreadInfo info = (ThreadInfo) iter.next();
				if (info.ruleContains(resource)) {
					return info;
				}
			}
			return null;
		}
	}
	
	public ISchedulingRule acquire(ISchedulingRule resourceRule, IFlushOperation operation, IProgressMonitor monitor) {
		ThreadInfo info = getThreadInfo();
		boolean added = false;
		synchronized (infos) {
			if (info == null) {
				info = new ThreadInfo(operation);
				Thread thisThread = Thread.currentThread();
				infos.put(thisThread, info);
				added = true;
				if(DEBUG) System.out.println("[" + thisThread.getName() + "] acquired batching lock on " + resourceRule); //$NON-NLS-1$ //$NON-NLS-2$
			}
		}
		try {
			return info.pushRule(resourceRule, monitor);
		} catch (OperationCanceledException e) {
			// The operation was cancelled.
			// If this is the outermost acquire then remove the info that was just added
			if (added) {
				synchronized (infos) {
					infos.remove(Thread.currentThread());
				}
			}
			throw e;
		}
	}
	
	/**
	 * Release the lock held on any resources by this thread. The provided rule must
	 * be identical to the rule returned by the corresponding acquire(). If the rule
	 * for the release is non-null and all remaining rules held by the lock are null,
	 * the the flush operation provided in the acquire method will be executed.
	 */
	public void release(ISchedulingRule rule, IProgressMonitor monitor) throws TeamException {
		ThreadInfo info = getThreadInfo();
		Assert.isNotNull(info, "Unmatched acquire/release."); //$NON-NLS-1$
		Assert.isTrue(info.isNested(), "Unmatched acquire/release."); //$NON-NLS-1$
		info.popRule(rule, monitor);
		synchronized (infos) {
			if (!info.isNested()) {
				Thread thisThread = Thread.currentThread();
				if(DEBUG) System.out.println("[" + thisThread.getName() + "] released batching lock"); //$NON-NLS-1$ //$NON-NLS-2$
				infos.remove(thisThread);
			}
		}
	}

	public void resourceChanged(IResource resource) {
		ThreadInfo info = getThreadInfo();
		Assert.isNotNull(info, "Folder changed outside of resource lock"); //$NON-NLS-1$
		info.addChangedResource(resource);
	}

	/**
	 * Flush any changes accumulated by the lock so far.
	 */
	public void flush(IProgressMonitor monitor) throws TeamException {
		ThreadInfo info = getThreadInfo();
		Assert.isNotNull(info, "Flush requested outside of resource lock"); //$NON-NLS-1$
		info.flush(monitor);
	}

	public boolean isWithinActiveOperationScope(IResource resource) {
		synchronized (infos) {
			return getThreadInfo(resource) != null;
		}
	}
}

Back to the top