Choice of Reentrantlock and synchronized
1 synchronized's drawbacks, simplifying code work, and good interaction with exception handling operations, but not flexible enough to control the thread, such as the inability to interrupt the waiting thread, or can not be the request to obtain a lock infinite wait, also can not implement the lock rule of non-blocking structure.
2 Reentrantlock, java5.0 is introduced later, the lock interface is implemented, providing the same mutex and memory visibility as the synchronized. java5.0 inside the performance advantage than the built-in lock is obvious, java6.0 inside almost, is a built-in lock supplement, not an alternative,
Public Interfance lock{
void Lock ();
void Lockinterruptibly () throws interruptedexception;//Interruptible acquired operation
Boolean trylock ();//polling lock to avoid deadlock occurrence
Boolean Trylock (Long timeout, timeunit unit);//timing lock to avoid the occurrence of deadlocks
void unlock ();
Condition newcondition ();
}
Use standard
Lock lock = new Reentrantlock ()
......
Lock.lock ();
try{
}catch () {
Perform an update operation
}finally{
Lock.unlock ();
}
Trylock, such as the need to acquire a lock on two objects at the same time to start the business,
if (Alock.trylock ())
try{
if (Block.trylock ())
try{
Perform business operations
}catch{
}finally{
Block.unlock ();
}
}catch{
}finally{
Alock.unlock ();
}
3 Reentrantreadwritelock Read-write lock, a resource can be accessed by multiple read operations, or accessed by a write operation, but not both. He allows multiple threads that perform read operations to access data structures, effectively improving program performance.
Pubilc Interface Readwritelock () {
Lock Readlock ();
Lock writelovk ();}
Package map based on read-write lock:
public class readwritemap{
Private final map<k,v> Map;
Private final Readwritelock lock = new Reentrantreadwritelock ();
Private final Lock R = Lock.readlock ();
Private final Lock w = Lock.writelock ();
Public Readwritemap (map<k,v> Map) {
This.map=map;
}
Public V put (K key,v value) {
W.lock ();
try{
Return Map.put (Key,value);
}catch{
}finally{
W.unlock ();
}
Public V get (K key) {
R.lock ();
try{
Return get (Key)
}catch{
}finally{
R.unlock ();
}
}
Java Multithreading Knowledge Comb 2