On synchronization of Boolean constants in Java multithreaded programming _java

Source: Internet
Author: User
Tags volatile

Multithreading concurrency can be achieved through synchronized statements in Java. Using a synchronized code block, the JVM guarantees that only one thread at a time can hold a lock on an object. The lock mechanism enables multiple threads to secure access to critical resources.

The synchronization code is written as follows:

Code 1:

Object obj = new Object (); 
... 
Synchronized (obj) { 
 //todo: Access critical Resource 
} 

Java multithreading is always full of traps, and if we use Boolean as the object to be synchronized, the following two scenarios may occur:

I think that to lock an object, the actual synchronization of the different objects.

Code 2:

Private volatile Boolean isTrue = false; 
 
Publich void Amethod () { 
 ... 
 Synchronized (isTrue) { 
  isTrue =!istrue; 
  TODO: Access critical resource 
  isTrue =!istrue; 
 } 
 ... 
} 

The above code is fine, because synchronized (isTrue) can only have one thread access to the critical resource at the same time, but that's not the case. Because false and true are two constants that correspond to two different objects. When IsTrue produces changes, it is likely that different threads will synchronize different objects. Java's auto boxing turns false to Boolean.false, which turns TRUE to boolean.true (which also means that if you change false here to boolean.false the result is the same). Write a test code for the above situation as follows:

Code 3:

 public class Booleantest {private volatile Boolean isTrue = Boolean.false; False is the same. public void Amethod () {for (int i=0;i<10;i++) {Thread t = new Thread () {public V 
            OID Run () {synchronized (isTrue) {isTrue =!istrue; 
            System.out.println (Thread.CurrentThread (). GetName () + "-istrue=" + isTrue); 
              try{Double ran = 1000 * math.random (); 
            Thread.Sleep (Ran.intvalue ()); }catch (Interruptedexception e) {} if (!istrue) System.out.println (Thread.CurrentThread (). GetName 
 
            () + "-Oh, no!"); 
          IsTrue =!istrue; 
      } 
        } 
      }; 
    T.start (); 
    } public static void Main (String ... args) {booleantest bt = new Booleantest (); 
  Bt.amethod (); } 
} 

Run the code above and you will see "-Oh, no!" at a time, indicating that different threads are entering the synchronized code block at the same time.

Two. The synchronization is considered to be a different object, actually an object.

Sometimes we may want to synchronize on multiple objects, and if you use a Boolean as a synchronized object, it is likely to cause two synchronized blocks that should not have been related to use the same object's locks. Examples are as follows:

Code 4:

Private volatile Boolean Aboolean = Boolean.false; 
 
Private volatile Boolean Anotherboolean = false; 
 
public void Amethod () { 
 ... 
 Synchronized (Aboolean) { 
  //todo: Access critical resource 1 
 } 
 ... 
} 
 
public void Anothermethod () { 
 ... 
 Synchronized (Anotherboolean) { 
  //todo: Access critical resource 2 
 } 
 ... 
} 

Suppose that the original Amethod and Anothermethod are called by two threads that have no relationship to each other. However, because Boolean.false and false point to the same object, access to critical resource 2 may be blocked by critical resource 1 (and vice versa).

The above two scenarios show that when using a synchronized block, try not to use a Boolean object as a synchronized object, or you may have unexpected problems, or the future of code modification caused by traps.

From then on, you can see that any synchronization of constants is risky. If you must synchronize a Boolean, be sure to create a Boolean object with the new operator.

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.