The difference between synchronized and Lock, volatile of

The difference between synchronized and volatile

  • volatile lightweight thread synchronization is achieved, and therefore better performance in synchronized volatile
  • voaltile modification variable, synchronized code blocks and modification methods
  • Multithreading does not block access volatile happen, but it may block access to synchronized
  • volatile data can ensure visibility, but not guaranteed atomicity; both synchronized and guarantee atomic, or indirectly guaranteed visibility.
  • The solution is volatile among multiple threads visibility of variables, and Synchronized solve is synchronization of access to resources among multiple threads

Difference synchronized with the ReentrantLock

  • Lock are reentrant
  • is dependent on the JVM to achieve synchronized; and reentrantLock the JDK is implementation-dependent, the API level, required Lock () and unLock () method with the try / finally statement block to complete.
  • reentrantLock than synchronized three functions: interruptible wait, can achieve a fair lock, enabling selective notification (lock can bind multiple conditions).

 

Interruptible wait: wait interruptible means thread can choose to give up waiting instead to deal with other things, ReenTrantLock by lock.lockInterruptibly () to achieve.

Fair locks: first thread is waiting to acquire the lock. Synchronized only non-fair locks. ReenTrantLock non-default fairness, may be specified by ReentrantLock (boolean fair) constructor method is fair or unfair latch lock.

Selective Acknowledgment: Synchronized keywords and wait () and notify / notifyAll () method may be implemented in conjunction with wait / notification mechanism, but the thread is notified by the JVM is randomly selected. Synchronized Lock equivalent to the entire object only a single condition object, all of its threads are registered in a target body. When the thread starts notifyAll (), need to notify all waiting threads, no right to choose, will cause great efficiency. The ReenTrantLock can make use of Condition objects for selective notification, better flexibility. For example: You can create multiple Condition instances (ie objects monitor) Lock in a subject, the thread thread notifications can be registered as specified in Condition, which can have a choice, even if signalAll () method will only wake Sign thread all waiting in the Condition instance.

Reentrant locks: they can get their own internal lock again. For example: a thread to acquire a lock of an object, and has not released when the thread again wants to acquire the object lock you can still get in, if not reentrant locks, it would cause a deadlock.

Guess you like

Origin www.cnblogs.com/jxxblogs/p/11928259.html