| ReadWriteLockRegistry.java |
1 /**
2 * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3 *
4 * The contents of this file are subject to the terms of the Liferay Enterprise
5 * Subscription License ("License"). You may not use this file except in
6 * compliance with the License. You can obtain a copy of the License by
7 * contacting Liferay, Inc. See the License for the specific language governing
8 * permissions and limitations under the License, including but not limited to
9 * distribution rights of the Software.
10 *
11 *
12 *
13 */
14
15 package com.liferay.portal.kernel.concurrent;
16
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ConcurrentMap;
19 import java.util.concurrent.locks.Lock;
20 import java.util.concurrent.locks.ReadWriteLock;
21 import java.util.concurrent.locks.ReentrantReadWriteLock;
22
23 /**
24 * <a href="ReadWriteLockRegistry.java.html"><b><i>View Source</i></b></a>
25 *
26 * <p>
27 * Registry for {@link ReadWriteLock} objects with {@link ReadWriteLockKey} as
28 * keys. The behavior of acquiring and releasing locks is provided by a {@link
29 * ConcurrentHashMap}. This class is completely thread safe and ensures that
30 * only one {@link ReadWriteLock} exists per key.
31 * </p>
32 *
33 * @author Shuyang Zhou
34 * @see ReadWriteLock
35 * @see ReadWriteLockKey
36 */
37 public class ReadWriteLockRegistry {
38
39 public Lock acquireLock(ReadWriteLockKey<?> readWriteLockKey) {
40 ReadWriteLock readWriteLock = _readWriteLockMap.get(readWriteLockKey);
41
42 if (readWriteLock == null) {
43 ReadWriteLock newReadWriteLock = new ReentrantReadWriteLock();
44
45 readWriteLock = _readWriteLockMap.putIfAbsent(
46 readWriteLockKey, newReadWriteLock);
47
48 if (readWriteLock == null) {
49 readWriteLock = newReadWriteLock;
50 }
51 }
52
53 if (readWriteLockKey.isWriteLock()) {
54 return readWriteLock.writeLock();
55 }
56 else {
57 return readWriteLock.readLock();
58 }
59 }
60
61 public void releaseLock(ReadWriteLockKey<?> readWriteLockKey) {
62 if (readWriteLockKey.isWriteLock()) {
63 _readWriteLockMap.remove(readWriteLockKey);
64 }
65 }
66
67 private ConcurrentMap<ReadWriteLockKey<?>, ReadWriteLock>
68 _readWriteLockMap = new ConcurrentHashMap
69 <ReadWriteLockKey<?>, ReadWriteLock>();
70
71 }