Java Thread Safety synchronized

Source: Internet
Author: User
Tags object object volatile

One, thread safety issues:

The principle of concurrent programming: The purpose of designing concurrent programming is to make the program achieve higher execution efficiency, but there must be no data consistency (data accurate) problem, if the concurrent program even the most basic execution results accuracy is not guaranteed, then the concurrent programming has no meaning.

Why does the data appear to be incorrect:

If a resource (variable, object, file, database) can be used by many threads at the same time, there will be data inconsistency problem, that is, we say the thread security problem. Such a resource is called a shared resource or a critical section.

As an example:

A shared variable m, which now has two threads adding up to it at the same time and executing 10,000 times each, then I expect the result to be 20000, but that's not actually the case. Look at the code:

 Packagecom.jalja.base.threadTest; Public classSynchronizedtestImplementsrunnable{Private Static volatile intM=0;  Public Static voidMain (string[] args) {Runnable run=Newsynchronizedtest (); Thread Thread1=NewThread (run); Thread thread2=NewThread (run);        Thread1.start ();        Thread2.start (); Try {            //Join () causes the main thread to wait for the thread to finish executing the following codeThread1.join ();        Thread2.join (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("M's final result:" +m); }     Public voidrun () { for(inti=0;i<10000;i++) {m++; }    }}

M is always less than 20000 regardless of how many times it runs. Why does it come to this end? When the thread Thread1 writes the result of the m++ to memory, the thread thread2 has read the value of M from memory, and the + + operation on that value (time-out), and finally writes the M=1 to memory (the THREAD1 value of m=1 calculation may be overwritten, It may also appear that the Thread1 overrides the Thread2 value). It is inevitable that such a result will occur.
How to control the problem of data accuracy caused by multi-threaded operation sharing data? Using the "Serialize access critical resource" scenario, at the same time, only one thread can access the critical resource, also known as synchronous mutex access, which means that our shared resources can only be used by one thread at a time, and once that resource is used by the thread, other threads will not have the use rights. In Java, there are two ways to achieve synchronous mutex access: synchronized and lock.

second, mutually exclusive access to the synchronized (synchronous method or synchronization block)

Mutex: As the name implies, is a lock for mutual access purposes.

As a simple example: if you add a mutex to a critical resource, when a thread accesses that critical resource, the other threads can only wait.

In Java, each object has a lock tag (monitor), also known as a monitor, when multiple threads access an object at the same time, only the thread that owns the object's lock can access it.

In Java, you can use the Synchronized keyword to mark a method that needs to be synchronized or to synchronize a block of code, and when a thread invokes the object's synchronized method or accesses a synchronized block of code, the thread obtains the lock on that object. Other threads are temporarily unable to access this method, and the thread will not release the lock on the object until the method is executed or the code block is executed, and other threads can execute the method or block of code. In this way to reach the point we mentioned above at the same time, only one thread can access the critical resource .

Synchronized usage:

1. Synchronizing code blocks

synchronized (synobject) {             }

Usage: Synchronized acts on a property of a given object or class, so whenever a thread executes this block of code, it asks for the lock of the object Synobject first, and if the lock is already occupied by another thread, then the new thread can only wait. This makes it impossible for other threads to access the code block at the same time.

 Packagecom.jalja.base.threadTest; Public classSynchronizedtestImplementsrunnable{Private Static volatile intM=0;  Public Static voidMain (string[] args) {Runnable run=Newsynchronizedtest (); Thread Thread1=NewThread (run); Thread thread2=NewThread (run);        Thread1.start ();        Thread2.start (); Try {            //Join () causes the main thread to wait for the thread to finish executing the following codeThread1.join ();        Thread2.join (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("M's final result:" +m); }     Public voidrun () {synchronized( This) {             for(inti=0;i<10000;i++) {m++; }        }    }}

The code uses the current object as a mutex, and below we use a property of the class as the mutex.

 Packagecom.jalja.base.threadTest; Public classSynchronizedtestImplementsrunnable{Private Static volatile intM=0; Private Object object=new  object ();  Public Static voidMain (string[] args) {Runnable run=Newsynchronizedtest (); Thread Thread1=NewThread (run); Thread thread2=NewThread (run);        Thread1.start ();        Thread2.start (); Try {            //Join () causes the main thread to wait for the thread to finish executing the following codeThread1.join ();        Thread2.join (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("M's final result:" +m); }     Public voidrun () {synchronized(object) { for(inti=0;i<10000;i++) {m++; }        }    }}

1. Synchronization method

 Packagecom.jalja.base.threadTest; Public classSynchronizedtestImplementsrunnable{Private Static intM=0;  Public Static voidMain (string[] args) {Runnable run=Newsynchronizedtest (); Thread Thread1=NewThread (run); Thread thread2=NewThread (run);        Thread1.start ();        Thread2.start (); Try {            //Join () causes the main thread to wait for the thread to finish executing the following codeThread1.join ();        Thread2.join (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("M's final result:" +m); }     Public synchronized voidrun () { for(inti=0;i<10000;i++) {m++; }    }}

In this code, synchronzied acts on an instance method, which means that when the thread enters the run () method, it must obtain the current object instance lock, in this case the object instance lock is run. Here to remind you to take a serious look at the implementation of the main function in the three code, where we use runnable to create two threads, and these two threads point to the same Runnable interface instance, in order to ensure that two threads in the work, the same object lock, so as to ensure thread safety.

Java Thread Safety synchronized

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.