用户可以根据需要建立自己的全局单例类,而把这个 KeyMap 类作为背后的工具类使用,达到根据某类型的键来锁定保护数据的目的。
最初的设计来源于惑惑的博客 http://blog.csdn.net/icebamboo_moyun/article/details/9391915
感谢他的无私分享。
/*
* Copyright 2013 (raistlic@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
/**
* This class allows multiple threads to lock against a key of the specified type,
* based on the {@code equals()} contract defined in {@link java.lang.Object}
* class, in a reentrant manner.
*
* <p/>
* All methods defined in this class, including the static factory methods, are
* thread safe.
*
* @param <K> the specified key type
*
* @author icebamboo_moyun, raistlic
*/
public abstract class LockMap<K> {
/**
* This method creates and exports a {@code LockMap} instance that is "Garbage
* Collector friendly", that is, it releases any lock references that is no
* longer used. It is recomm