Java multithreading-Do not sync Boolean constants test code __java

Source: Internet
Author: User
Tags volatile

Java multithreading-Do not synchronize Boolean constants

Put forward two points of view:

A 1.Boolean object assignment of True and false changes the object that is pointed to.

Test code:

Private volatile Boolean isTrue = Boolean.false; False is the same here. Public 
	void Amethod () {for
		(int i = 0; i < 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;
						System.out.println (Thread.CurrentThread (). GetName () + "Exit");}}
			;
			T.start ();
		}
	

One of the results of the operation:

Thread-0-Istrue=true
Thread-1-istrue=false
Thread-0-Oh, no!
Thread-0 exit
Thread-9-istrue=false
Thread-1-Oh, no!
Thread-1 exit
Thread-9 exit
Thread-8-istrue=true
Thread-8 exit
Thread-7-istrue=true
Thread-7 Exit
Thread-6-istrue=true
Thread-6 exit
Thread-5-istrue=true
Thread-5 exit
Thread-4- Istrue=true
Thread-4 exit
Thread-3-istrue=true
Thread-3 exit
Thread-2-Istrue=true
Thread-2 exit

According to General logic, IsTrue is shared as a shared object by 10 threads, each thread's Run method code is istrue, should be thread safe, should not output Oh, no!, but the output is just the opposite;

Analysis Reason: IsTrue initialization is assigned to boolean.false this constant, enter run, synchronized lock is boolean.false this object, after the non, IsTrue point to change, point to boolean.true this constant, the following thread into the run After synchronized lock the Boolean.true this object, so that no thread mutex occurs, output Oh, no!, is not up to thread-safe purpose.

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

Import Java.util.Random;  
	public class Booleantest {private volatile Boolean Aboolean = False;//boolean.false;
	Private volatile Boolean Anotherboolean = false;
	Private Long T1 = System.currenttimemillis ();
		public void AMethod2 () {final Random Random = new Random ();
					for (int i = 0; i < i++) {thread t = new Thread () {public void run () {int val = random.nextint (); if (val% 2 = 0) {synchronized (Aboolean) {System.out.println (Thread.CurrentThread (). GetName () + "ABo
							Olean_costmills: "+ (System.currenttimemillis ()-t1));
							T1 = System.currenttimemillis ();
							try {thread.sleep (100);
							catch (Interruptedexception e) {e.printstacktrace ();  }} else {synchronized (Anotherboolean) {System.out.println thread.currentthread (). GetName () +
							"Anotherboolean_costmills:" + (System.currenttimemillis ()-t1));
							T1 = System.currenttimemillis ();
	try {thread.sleep (200);						catch (Interruptedexception e) {e.printstacktrace ();
			}
						}
					}
				}
			};
		T.start ();
		} public static void Main (String ... args) {booleantest bt = new Booleantest ();
	BT.AMETHOD2 ();
 }
}
Possible output:

Thread-0 anotherboolean_costmills:0
Thread-9 aboolean_costmills:204
Thread-8
aboolean_costmills:110 Thread-7 aboolean_costmills:109
Thread-6 anotherboolean_costmills:110
Thread-5 anotherboolean_costmills : 204
Thread-4 aboolean_costmills:219
Thread-1 aboolean_costmills:110
Thread-3
Thread-2 aboolean_costmills:110

Analysis Reason: Obviously program adds two lock Aboolean,anotherboolean, the code that executes these two locks should be non-interference, but print shows: If the previous execution is Aboolean, followed by Anotherboolean, Need to wait 110ms (normal should not wait); If the previous Anotherboolean, the back Aboolean, waiting for 204ms (normal should not wait); This shows that the two executions have been mutually exclusive. , because Aboolean and Anotherboolean point to the same object boolean.false; In fact, Boolean.false and false point to the same object, so Aboolean assignment Boolean.false or FALSE, the effect is the same.


In summary: Try not to use a Boolean object as a synchronized object, or there may be unexpected problems, or the future code modification caused by traps.

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.