Static variables, instance variables, local variables for Java thread safety issues

Source: Internet
Author: User

Java multithreaded programming, there are many thread security issues, as to what is thread safety, it is difficult to give an easy-to-understand concept, as in the Java Concurrency programming practice, said:

Wrote

Static variable: thread is not secure.

A static variable is a class variable, located in the method area, shared for all objects, shares a portion of memory, and once the static variable is modified, the other objects are visible to the modification, so the thread is not secure.

Instance variables: Singleton mode (only one object instance exists) thread is not secure, not singleton thread safe.

Instance variables are private to the object instance, allocated in the heap of the virtual machine, if there is only one instance of this object in the system, in multi-threaded environment, "like" static variable, after being modified by a thread, other threads are visible to the modification, so the thread is not safe, if each thread executes in a different object, The modification of the instance variable between the object and the object will not affect each other, so thread safety.

Local variables: thread safety.

Each thread executes a local variable in the working memory of its own stack frame and is not shared between threads, so there is no thread-safety issue.

Static variable thread safety problem simulation:

----------------------------------------------------------------------------------

1 /**  2 * Thread safety problem simulation execution3   *  ------------------------------  4 * Thread 1 | Thread 25   *  ------------------------------  6 * static_i = 4; | Wait7 * static_i = 10; | wait8 * wait | static_i = 4; 9 * static_i * 2; | WaitTen   *  -----------------------------  One  * */   A  Public classTest implements Runnable - {   -     Private Static intStatic_i;//Static Variables the        -      Public voidRun () -     {   -Static_i =4;  +System. out. println ("["+Thread.CurrentThread (). GetName () -+"] Gets the value of the static_i:"+static_i);  +Static_i =Ten;  ASystem. out. println ("["+Thread.CurrentThread (). GetName () at+"] Gets the value of the static_i*3:"+ static_i *2);  -     }   -        -      Public Static voidMain (string[] args) -     {   -Test T =NewTest ();  in         //start as many threads as possible to simulate problems easily -          for(inti =0; I < the; i++)   to         {   +             //T can be replaced with new Test () to ensure that each thread executes in a different object, as a result -             NewThread (T,"Threads"+i). Start ();  the         }   *     }   $}

According to the scenario that is simulated in the code comment, when thread 1 executes static_i = 4; Static_i = 10; After that, thread 2 gets the execution right, static_i = 4;  Then when thread 1 gets execution execution static_i * 2; Inevitably the output results are 4*2=8, according to this simulation, we may see the output as a result of 8 in the console.

Wrote
[Thread 27] Gets the value of static_i:4  [thread 22] getsThe value of Static_i : [Thread 28] Gets the value of static_i:4  [thread 23] getsThe value of static_i:8  [Thread 29] Gets the value of static_i: 4 [Thread 30] Gets the value of static_i: 4 [Thread 31] Gets the value of static_i: 4 [Thread 24] Getsthe value of static_i:

Looking at the red-labeled parts, we did have our expectations, as well as our conclusions.

Instance variable thread safety problem simulation:

----------------------------------------------------------------------------------

1  Public classTest implements Runnable2 {  3     Private intInstance_i;//instance Variable4       5      Public voidRun ()6     {  7Instance_i =4; 8System. out. println ("["+Thread.CurrentThread (). GetName ()9+"] Gets the value of the instance_i:"+instance_i); TenInstance_i =Ten;  OneSystem. out. println ("["+Thread.CurrentThread (). GetName () A+"] Gets the value of the instance_i*3:"+ instance_i *2);  -     }   -        the      Public Static voidMain (string[] args) -     {   -Test T =NewTest ();  -         //start as many threads as possible to simulate problems easily +          for(inti =0; I < the; i++)   -         {   +             //Each thread runs on the object T, simulating a single case A             NewThread (T,"Threads"+i). Start ();  at         }   -     }   -}

According to the analysis at the beginning of this article, as with static variables, each thread is modifying an instance variable of the same object, and there is definitely a thread-safety issue.

Wrote

[Thread 66] Gets the value of Instance_i : [Thread 33] GetsThe value of instance_i:  [Thread 67] Gets the value of instance_i:4[Thread 34] Get Instance_i Value:8   [Thread 35] getsthe value of instance_i:  [thread 68] Gets the value of instance_i:4 

Look at the red font, the instance variable thread is not safe in a single case.

Add the new thread (T, "thread" + i). Start (), and change to new thread (new Test (), "thread" + i). Start (); Simulates a non-singleton case where there is no thread safety issue.

Local variable threading Security problem simulation:

----------------------------------------------------------------------------------

1  Public classTest implements Runnable2 {  3      Public voidRun ()4     {  5         intLocal_i =4; 6System. out. println ("["+Thread.CurrentThread (). GetName ()7+"] Gets the value of the local_i:"+local_i); 8Local_i =Ten; 9System. out. println ("["+Thread.CurrentThread (). GetName ()Ten+"] Gets the value of the local_i*2:"+ local_i *2);  One     }   A        -      Public Static voidMain (string[] args) -     {   theTest T =NewTest ();  -         //start as many threads as possible to simulate problems easily -          for(inti =0; I < the; i++)   -         {   +             //Each thread runs on the object T, simulating a single case -             NewThread (T,"Threads"+i). Start ();  +         }   A     }   at}

The console does not have exception data.

---------------------------------------------------------------

The above is just a simple example to show the static variables, instance variables, local variables, such as thread safety problems,

Without the underlying analysis, the next article will dissect the underlying thread problem.

Static methods are thread-safe
first look at a class  Public class   test{publicstatic  string Hello (String str) {      string tmp=   "" ;      TMP  =  tmp+str;       return tmp;  }} Will the Hello method have multiple thread safety issues? No!! Static methods There is no thread-safety issue if static variables are not used. Why is it? Because of variables declared within a static method, each thread is called to create a new copy without sharing a single storage unit. For example, the TMP here, each thread will create its own copy, so there will be no threads security issues Note that static variables, because the class is loaded with a storage area, each thread is shared with this store, so if you use static variables in static methods, this will be a thread security problem! Summary: As long as the method contains static variables, it is non-thread-safe

Static variables, instance variables, local variables for Java thread safety issues

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.