1. Semaphore 的 acquire() 方法和acquireUninterruptibly() 方法
acquire() 方法是可被中断的。例如一个线程Thread A正在调用了semaphore的acquire() 方法,而另一个线程Thread B 调用interrupt()打断了Thread A ,
那么Thread A中则可以抛出一个InterruptedException。
而 acquireUninterruptibly()方法是不可被中断的。那就意味着如果Thread A正在调用了semaphore的acquireUninterruptibly() 方法,然后Thread B通过调用interrupt()方法中断Thread A,那么Thread A中不会抛出InterruptedException异常,仅仅是当Thread A 的acquireUninterruptibly() 方法返回后它回有个中断的状态设置。
2. 关于key级别锁的一种简单实现
public void executeInKeyLock(String lockKey, Runnable runnable) {
synchronized(lockKey.intern()) {
runnable.run();
}
}
使用String的intern()方法作为key: 可以确保返回的字符串是一个全局独一无二的对象,所以它可以用作vm-instance-wide互斥锁。不要担心内存泄露;这些字符串将被gc如果没有其他线程引用它。但是注意包括Java6及以上的JDK中,该池是保存在PermGen空间而不是heap, 所以你可能会增加它的大小。
如果在你的虚拟机中的其他代码里使用了同一个字符串进行锁,但是完全出于不同的原因, 虽然这种情况是不太可能的,但是你可以通过使用前缀来避免这种事情的发生,例如executeInKeyLock(this.getClass(). getname()+“_”+ myLockKey);
但是网上也有对这种方法持反对意见:觉得String.intern()使用是要付出一点过的代价的,因为不同VM之间对这个的实现可能存在差别,所有要谨慎使用该方式。
于是可以对上面的方法稍作改进,锁定的key转换一下,由String转换为Mutex
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
/**@author McDowell*/
public class IdMutexProvider {
private final Map mutexMap = new WeakHashMap();
/**Get a mutex object for the given (non-null) id.*/
public Mutex getMutex(String id) {
if(id==null) {
throw new NullPointerException();
}
Mutex key = new MutexImpl(id);
synchronized(mutexMap) {
WeakReference ref = (WeakReference) mutexMap.get(key);
if(ref==null) {
mutexMap.put(key, new WeakReference(key));
return key;
}
Mutex mutex = (Mutex) ref.get();
if(mutex==null) {
mutexMap.put(key, new WeakReference(key));
return key;
}
return mutex;
}
}
/**Get the number of mutex objects being held*/
public int getMutexCount() {
synchronized(mutexMap) {
return mutexMap.size();
}
}
public static interface Mutex {}
private static class MutexImpl implements Mutex {
private final String id;
protected MutexImpl(String id) {
this.id = id;
}
public boolean equals(Object o) {
if(o==null) {
return false;
}
if(this.getClass()==o.getClass()) {
return this.id.equals(o.toString());
}
return false;
}
public int hashCode() {
return id.hashCode();
}
public String toString() {
return id;
}
}
}
改进后的方法为:
public void executeInKeyLock(String lockKey, Runnable runnable) {
IdMutexProvider imp = new IdMutexProvider();
synchronized(imp.getMutex(lockKey)) {
runnable.run();
}
}
3. ConcurrentMap 的putIfAbsent方法的使用
put-if-absent 操作以原子性方法 putIfAbsent(K key, V value) 的形式存在。需要注意的是putIfAbsent 方法是有返回值的,并且返回值很重要。
“如果(调用该方法时)key-value 已经存在,则返回那个 value 值。如果调用时 map 里没有找到 key 的 mapping,返回一个 null 值”
虽然putIfAbsent 是原子性的,但是当多线程中进行“取” 和 “存” 两个操作的复合操作时,为保证并发情况下代码行为的准确性,还是需要判断返回值的。
4. key级别锁的更优化实现方法
先贴代码,一个keylocker的工具类
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;
/**
* This class allows multiple threads to lock against a string key
*
* Created by hiperion on 2017/3/15.
*/
public class KeyLocker {
private ConcurrentMap<String, Semaphore> semaphoreMap = new ConcurrentHashMap<String, Semaphore>();
public KeyLocker(){}
public void acquire(String key) throws Exception {
if( key == null )
throw new NullPointerException();
Semaphore semaphore = new Semaphore(1, true);
Semaphore semaphoreExist = semaphoreMap.putIfAbsent(key, semaphore);
if(semaphoreExist == null){
semaphoreExist = semaphore;
}
semaphoreExist.acquireUninterruptibly();
}
public void release(String key) throws Exception{
if( key == null )
throw new NullPointerException();
Semaphore semaphore = semaphoreMap.get(key);
if(semaphore != null){
semaphore.release();
}
}
}
使用方法,继续代码
@Override
public <E> E getData(String key) {
try {
keyLocker.acquire(key);
//编写根据key获得数据的代码
return data;//根据key获得的数据
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
keyLocker.release(key);
}catch (Exception e){
e.printStackTrace();
}
}
}
That’s all. Have fun!

本文探讨了Semaphore的两种获取方法,提出了一种基于String.intern()的简单key级别锁实现方案,并对其进行了优化。此外,还介绍了ConcurrentMap的putIfAbsent方法的正确使用方式,以及一种更为高效的key级别锁实现。
10万+

被折叠的 条评论
为什么被折叠?



