Qin Xiaobo writes high-quality code-151 suggestions for improving Java programs The thread in the book explains the error.

Source: Internet
Author: User

Location: Suggested 127:lock and synchronized are not the same

First, this article is conceptually corrected:

Invoke the Java source code in the opening note about Reentrantlock:

* A reentrant mutual exclusion {@link Lock} with the same basic
* Behavior and semantics as the implicit monitor lock accessed using
* {@code Synchronized} methods and statements, but with extended
* capabilities.

According to the instructions: The two locking method is the same basic behavior and semantics, only the expression and functional extensibility differences, so the proposed theory is wrong.

The following code snippet execution differences and the original author's interpretation errors mainly occur in the following areas:

1. Reentrantlock and synchronized are object-level, and none of them are class-level, so they only work on specific objects that are affected by the code.

such as synchronized public void Read () {

Some executing code region

} is implicitly locking this;

Equivalent to:

Lock lock = new Reentrantlock ();

public void Read () {

Lock.lock ();

try{

Some executing code region

}finally{

Lock.unlock ();

}

}

The difference between the two is a monitorthis, a monitor lock object.

The more special cases are:

Synchronized Publi static execute () {

  

}

The class object is locked by a. Class object.

Inconsistencies in the following are mainly seen in the synchronized lock on "A",

Constant string objects are globally unique throughout the life cycle, therefore, the global effect of "a" is not only in the sub-class, but in a timely manner any synchronized ("a") will have a synchronous effect, which violates the closure principle, so there is a huge programming risk.

Quoted code error:

This article refers to the two-paragraph code to understand the behavior inconsistencies in both ways.

Simply enumerate and point out the problem here:

Class1:lock

/*****************************************************************************/

Class Task {

public void dosomething () {

try{

Thread.Sleep (2000);

}catch (Exception e) {

Exception handling

}

StringBuilder sb = new StringBuilder ();

Thread Name:

Sb.append ("Thread Name:" + Thread.CurrentThread (). GetName ());

Run time stamp

Sb.append (", Execution Time:" + calendar.getinstance (). Get (+) + "s");

System.out.println (Sb.tostring ());

}

}

/****************************************************************************/

Class Taskwithlock extends Task implements runnable{

Private Final lock lock = new Reentrantlock ();

@Override

public void Run () {

try{

Start locking

Lock.lock ();

DoSomething ();

}finally{

Release lock

Lock.unlock ();

}

}

}

/***************************************************************************/

Class Taskwithsync extends Task implements runnable{

@Override

public void Run () {

Internal cable

Synchronized ("A") {

DoSomething ();

}

}

}

public static void Runtasks (CLASS<? extends Runnable> Clazz) throws Exception {

try{

Executorservice es = Executors.newcachedthreadpool ();

SYSTEM.OUT.PRINTLN ("* * * Start Execution" + clazz.getsimplename () + "task completed-----------------\ n");

Start three threads

for (int i=0; i<3; i++) {

Es.submit (Clazz.newinstance ());

}

TimeUnit.SECONDS.sleep (10);

System.out.println ("--------" + clazz.getsimplename () + "task execution completed------\ n");

Close the Actuator

}finally{

Es.shutdown ();

}

}

Qin Xiaobo writes high-quality code-151 suggestions for improving Java programs The thread in the book explains the error.

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.