Java synchronized and (reentrantlock) differences

Source: Internet
Author: User
Tags mutex

Original: http://blog.csdn.net/zheng548/article/details/54426947

Difference One: API level

syschronized use

The synchronized can be modified or decorated with code blocks.

The synchronized modifies the method as follows:

Synchronized modifies a method, this method is called synchronous method public synchronized void Test () {    //method body}

When synchronized modifies a block of code, it includes two parts: a reference to the lock object and a block of code protected by the lock. As shown below:

Synchronized (0bject) {    ///parentheses indicate the object that needs to be locked//The     thread executes when it locks on object      }

Reentrantlock use

public class Test () {    private Lock lock=new reentrantlock ();    public void TestMethod () {        try{            lock.lock ();            Code        }          finally{            lock.unlock ();   }}}            

Difference Two: Wait can be interrupted

"In-depth understanding of Java Virtual Machines" by reference to Zhou Zhiming Page 392

Waiting for interruptible means that when the thread holding the lock does not release the lock for a long time, the waiting thread can choose to discard the wait and handle other things instead. The wait feature is useful for processing synchronous blocks that have a very long execution time.

Specifically, if there are two threads in the business code, Thread1 Thread2. Suppose Thread1 acquires a lock on object, Thread2 waits for Thread1 to release the lock for object.

    • Use synchronized. If Thread1 is not released, Thread2 will wait and not be interrupted. Synchronized can also be said to be the atomic built-in locking mechanism provided by Java. The internal lock plays the role of the mutex (mutual exclusion lock, mutex) when a thread refers to the lock while another thread blocks waiting.

    • Use Reentrantlock. If Thread1 does not release, Thread2 waits a long time, can interrupt wait, turn to do other things.

Difference Three: Fair lock

"In-depth understanding of Java Virtual Machines" by reference to Zhou Zhiming Page 392

A fair lock is when multiple threads are waiting for the same lock, and the lock must be obtained sequentially in the order in which they are requested, while an unfair lock does not guarantee this. When a lock is released, any thread that waits for a lock has the opportunity to acquire a lock. The synchronized lock is a non-fair lock, and Reentrantlock is also an unfair lock by default, but a fair lock can be required by a constructor with a Boolean value.

Difference Four: Bind multiple conditions

Reentrantlock can bind multiple condition objects at the same time, just call the Newcondition method multiple times.

In synchronized, the Wait and notify () or Notifyall () methods of the lock object can implement an implied condition. But if you want to associate a condition with Duyu, you have to add a lock.

Difference Five: Performance

In JDK 1.5, synchronized also has a lot of room for optimization. There are many optimizations for locking in JDK 1.6, and the synchronized and Reentrantlock performance are basically flat. Virtual machines are more inclined to native synchronized in future improvements.

Add:

Each object in the ①java has a lock (lock) or is called a monitor.

②reentrantlock and synchronized hold different object monitors.

③ if the synchronized method is static, then when the thread method is modified, it is not the object that the Synchronized method resides in, but the class object that corresponds to the object of the Synchronized method. Because in Java, no matter how many objects a class has, these objects deal with a unique class object. Therefore, when a thread accesses two static,synchronized methods of two objects of the same class separately, it is executed sequentially, that is, one thread executes first and the other begins.

The ④synchronized method is a coarse-grained concurrency control, with only one thread executing the Synchronized method at a time, and synchronized fast is a fine-grained concurrency control. Only the code in the block is synchronized, within the method, and beyond the synchronized block can be accessed concurrently by multiple threads.

After compiling the ⑤synchronized keyword, the monitorenter and monitorexit Two bytecode instructions are formed before and after the synchronization block, and the operand is the counter of the lock.

⑥ the same point: both are reentrant. A reentrant value is the same thread that attempts to acquire the lock it occupies more than once, and the request succeeds. When released, the lock is released until the number of flushes is zeroed out.

Java synchronized and (reentrantlock) differences

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.