Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 764c6b69a8c6c647dccd972e0e96a57f3e360593 (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
/*******************************************************************************
 * Copyright (c) 2012 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.osgi.internal.container;

import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class LockSet<T> {
	private final Map<T, ReentrantLock> locks = new WeakHashMap<T, ReentrantLock>();
	private final Object monitor = new Object();
	private final boolean reentrant;

	public LockSet(boolean reentrant) {
		this.reentrant = reentrant;
	}

	public boolean lock(T t) {
		ReentrantLock lock = getLock(t);
		lock.lock();
		if (reentrant)
			return true;
		if (lock.getHoldCount() > 1) {
			lock.unlock();
			return false;
		}
		return true;
	}

	public boolean tryLock(T t) {
		ReentrantLock lock = getLock(t);
		boolean obtained = lock.tryLock();
		if (obtained) {
			if (reentrant)
				return true;
			if (lock.getHoldCount() > 1) {
				lock.unlock();
				return false;
			}
		}
		return obtained;
	}

	public boolean tryLock(T t, long time, TimeUnit unit) throws InterruptedException {
		ReentrantLock lock = getLock(t);
		boolean obtained = lock.tryLock(time, unit);
		if (obtained) {
			if (reentrant)
				return true;
			if (lock.getHoldCount() > 1) {
				lock.unlock();
				return false;
			}
		}
		return obtained;
	}

	public void unlock(T t) {
		synchronized (monitor) {
			ReentrantLock lock = locks.get(t);
			if (lock == null)
				throw new IllegalStateException("No lock found."); //$NON-NLS-1$
			lock.unlock();
		}
	}

	private ReentrantLock getLock(T t) {
		synchronized (monitor) {
			ReentrantLock lock = locks.get(t);
			if (lock == null) {
				lock = new ReentrantLock();
				locks.put(t, lock);
			}
			return lock;
		}
	}
}

Back to the top