Java thread security-correct synchronized keyword usage

Source: Internet
Author: User

Java thread security: the usage of the synchronized keyword is unknown today. The synchronized keyword is used.CodeThread Synchronization is safe.

Tested. It is totally wrong. Synchronized must be correctly used to ensure real thread security... Although I knew this method, I always thought that I was using the wrong method because of laziness.

It seems that the Foundation has not been laid. Review is still required! It is unforgivable to make such mistakes at work. You must know that all data that uses the synchronized keyword is sensitive! Sweat...

Post Code first:

 
Package com; public class threadtest {public static void main (string [] ARGs) {mythread M1 = new mythread (1); mythread m2 = new mythread (2); m1.start (); m2.start () ;}} final class mythread extends thread {private int val; Public mythread (INT v) {val = V ;} // This is actually a non-thread-safe public synchronized void print1 (INT v) {for (INT I = 0; I <100; I ++) {system. out. print (v) ;}} public void print2 (INT v) {// thread security synchronized (mythread. class) {for (INT I = 0; I <100; I ++) {system. out. print (v) ;}} public void run () {print1 (VAL); // print2 (VAL );}}

Just to be lazy and sweat...ProgramPersonnel are always lazy. Write less. I wrote mythread as an anonymous final internal class for convenient calling. It uses the most direct inheritance thread to implement a Thread class and defines the run () method to be run.

First, comment out the print2 () method to see how the result of print1 () is. Print1 () is a method defined using the synchronized keyword. I always thought this would also enable thread security. I am wrong.

Run the main () method directly. The result is as follows:

1212111121212121212121212121212121212121222222212121212...

Is the result of a series of 1 and 2 Cross printing. In my main method, M1 is run first and M2 is run, which shows that thread synchronization is not performed!

 
Mythread M1 = new mythread (1); mythread m2 = new mythread (2); m1.start (); m2.start ();

Next, comment out print1 () in the run method and run print2 ();

The console is printed as follows:

11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222

The thread is safe, and I always thought that I knew this writing method, but I didn't think much about it because of this writing code. Today I realized this error. It seems that sometimes it is good to be not lazy. It is important to lay a good foundation. A long-standing error corrected.

Let's take a look at the specific reasons.

The synchronized keyword can be used as a modifier of the function or as a statement in the function, that is, the synchronization method and synchronization statement block. If further classification is performed, synchronized can act on instance variables, object reference, static functions, and class literals (literal constants of class names.
Before proceeding, we need to clarify the following points:
A. no matter whether the synchronized keyword is added to the method or object, the lock it acquires is an object, instead of using a piece of code or function as a lock-and the synchronization method is likely to be accessed by objects in other threads.
B. Each object has only one lock associated with it.
C. Implementing synchronization requires a large amount of system overhead as a cost, and may even cause deadlocks. Avoid unnecessary synchronization control as much as possible.
Next we will discuss the impact of synchronized on code in different places:
Assume that P1 and P2 are different objects of the same class. This class defines synchronization blocks or Synchronization Methods in the following situations, and P1 and P2 can call them.
1. When synchronized is used as a function modifier, the sample code is as follows:

 
Public synchronized void methodaaa (){//.... }

This is the synchronization method. Which object is synchronized locked at this time? The lock is to call this synchronization method object. That is to say, when an object P1 executes this synchronization method in different threads, they are mutually exclusive to achieve synchronization. However, the other object P2 generated by the class to which this object belongs can call the method with the synchronized keyword.
The above sample code is equivalent to the following code:

Public void methodaaa () {synchronized (this) // (1 ){//..... }}

(1) What does this mean? It refers to the object that calls this method, such as P1. It can be seen that the synchronization method essentially acts on the object reference. -- The thread that obtains the P1 object lock can call the synchronization method of P1. For P2, the P1 lock has nothing to do with it, in this case, the program may also get rid of the control of the synchronization mechanism, resulting in data confusion!

2. Synchronization block. The sample code is as follows:

 
Public void method3 (someobject so) {synchronized (SO ){//..... }}

In this case, the lock is the so object. Whoever gets the lock can run the code it controls. When a specific object is used as the lock, you can write the program in this way, but when there is no clear object as the lock, just want to synchronize a piece of code, you can create a special instance variable (which must be an object) to act as a lock:

 
Class Foo implements runnable {private byte [] Lock = new byte [0]; // special instance variable public void methoda () {synchronized (LOCK ){//... }}//..... }

Note: creating a zero-Length byte array object is more economical than any other object-view the compiled bytecode: only three operation codes are required for generating a zero-Length byte [] object, object lock = new object () requires seven lines of operation code.
3. apply synchronized to the static function. The sample code is as follows:

 
Class Foo {public synchronized static void methodaaa () // synchronized static function {//.... } Public void methodbbb () {synchronized (FOO. Class) // class literal (Class Name literal constant )}}

the methodbbb () method in the Code uses class literal as the lock. It produces the same effect as the synchronized static function, and the obtained lock is very special, is the class of the object currently calling this method (class, instead of a specific object generated by this class ).
I remember seeing Foo in objective Java. class and p1.getclass () are used for synchronization locks. p1.getclass () cannot be used to lock this class. P1 refers to the object generated by the foo class.
it can be inferred that if a class defines the static function a of synchronized, it also defines the instance function B of synchronized, when the same object OBJ of this class accesses Methods A and B in multiple threads, the synchronization is not formed because their locks are different. The lock of method A is the object OBJ, and the lock of Method B is the class to which OBJ belongs.
Summary:
figuring out which object is locked by synchronized can help us design safer multi-thread programs.
there are also some tips to make the synchronized access to shared resources more secure:
1. define the private instance variable + its get method, instead of the public/protected instance variable. If a variable is defined as public, the object can directly obtain it and change it by bypassing the control of the synchronization method. This is also one of the standard implementations of JavaBean.
2. if the instance variable is an object, such as an array or an arraylist, the above method is still insecure, because after the External Object obtains the reference of this instance object through the get method, and direct it to another object, so this private variable also changes, it is not very dangerous. At this time, you need to add the get method with synchronized synchronization, and only return the clone () of this private object-in this way, the caller obtains the reference of the object copy.

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.