这篇博客文章演示了一种为每个字符串 id 惯用语实现互斥锁的方法。使用的 String id 用于表示 HttpSession id。
- 为什么我们需要在 Mutex 实例周围包裹一个 WeakReference ?从 String -> Mutex 创建一个 Map 不是更好吗?
为什么我们需要调用 put 两次?
public Mutex getMutex( String id ) { Mutex key = new MutexImpl( id ); synchronized( mutexMap ) { WeakReference<Mutex> ref = mutexMap.get( key ); if( ref == null ) { mutexMap.put( key, new WeakReference<Mutex>( key ) ); return key; } Mutex mutex = ref.get(); if( mutex == null ) { mutexMap.put( key, new WeakReference<Mutex>( key ) ); return key; } return mutex; } }