001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.concurrent;
016    
017    import java.util.concurrent.ConcurrentHashMap;
018    import java.util.concurrent.ConcurrentMap;
019    import java.util.concurrent.locks.Lock;
020    import java.util.concurrent.locks.ReadWriteLock;
021    import java.util.concurrent.locks.ReentrantReadWriteLock;
022    
023    /**
024     * <p>
025     * Registry for {@link ReadWriteLock} objects with {@link ReadWriteLockKey} as
026     * keys. The behavior of acquiring and releasing locks is provided by a {@link
027     * ConcurrentHashMap}. This class is completely thread safe and ensures that
028     * only one {@link ReadWriteLock} exists per key.
029     * </p>
030     *
031     * @author Shuyang Zhou
032     * @see    ReadWriteLock
033     * @see    ReadWriteLockKey
034     */
035    public class ReadWriteLockRegistry {
036    
037            public Lock acquireLock(ReadWriteLockKey<?> readWriteLockKey) {
038                    ReadWriteLock readWriteLock = _readWriteLockMap.get(readWriteLockKey);
039    
040                    if (readWriteLock == null) {
041                            ReadWriteLock newReadWriteLock = new ReentrantReadWriteLock();
042    
043                            readWriteLock = _readWriteLockMap.putIfAbsent(
044                                    readWriteLockKey, newReadWriteLock);
045    
046                            if (readWriteLock == null) {
047                                    readWriteLock = newReadWriteLock;
048                            }
049                    }
050    
051                    if (readWriteLockKey.isWriteLock()) {
052                            return readWriteLock.writeLock();
053                    }
054                    else {
055                            return readWriteLock.readLock();
056                    }
057            }
058    
059            public void releaseLock(ReadWriteLockKey<?> readWriteLockKey) {
060                    if (readWriteLockKey.isWriteLock()) {
061                            _readWriteLockMap.remove(readWriteLockKey);
062                    }
063            }
064    
065            private ConcurrentMap<ReadWriteLockKey<?>, ReadWriteLock>
066                    _readWriteLockMap = new ConcurrentHashMap
067                            <ReadWriteLockKey<?>, ReadWriteLock>();
068    
069    }