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:

It is difficult to write a definition of thread safety. There are many definitions, such as: "A class is thread safe when it can be called by multiple threads."

Do not repeat here, first give the static variables, instance variables, local variables in the multi-threaded environment of the thread safety conclusions, and then use the example to verify, please eyes peeled, wrong must investigate, otherwise fraught!

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:

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

Java code
  1. /**
  2. * Thread safety problem simulation execution
  3. *  ------------------------------
  4. * Thread 1 | Thread 2
  5. *  ------------------------------
  6. * Static_i = 4; | Wait
  7. * static_i = 10; | Wait
  8. * wait | Static_i = 4;
  9. * Static_i * 2; | Wait
  10. *  -----------------------------
  11. * */
  12. Public class Test implements Runnable
  13. {
  14. private static int static_i; Static variables
  15. public Void Run ()
  16. {
  17. Static_i = 4;
  18. System.out.println ("[" + Thread.CurrentThread (). GetName ()
  19. + "] Gets the value of the static_i:" + static_i);
  20. Static_i = 10;
  21. System.out.println ("[" + Thread.CurrentThread (). GetName ()
  22. + "] Gets the value of the static_i*3:" + static_i * 2);
  23. }
  24. public static void Main (string[] args)
  25. {
  26. Test T = new test ();
  27. //start as many threads as possible to simulate problems easily
  28. For (int i = 0; i < ; i++)
  29. {
  30. //t can be replaced with new Test () to ensure that each thread executes in a different object, as the result
  31. new Thread (t, "thread" + i). Start ();
  32. }
  33. }
  34. }

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] Gets the value of static_i*2:20
[Thread 28] Gets the value of Static_i: 4
[Thread 23] Gets the value of static_i*2: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] Gets the value of static_i*2:20

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

Instance variable thread safety problem simulation:

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

Java code
  1. Public class Test implements Runnable
  2. {
  3. private int instance_i; Instance variable
  4. public Void Run ()
  5. {
  6. Instance_i = 4;
  7. System.out.println ("[" + Thread.CurrentThread (). GetName ()
  8. + "] Gets the value of the instance_i:" + instance_i);
  9. Instance_i = 10;
  10. System.out.println ("[" + Thread.CurrentThread (). GetName ()
  11. + "] Gets the value of the instance_i*3:" + instance_i * 2);
  12. }
  13. public static void Main (string[] args)
  14. {
  15. Test T = new test ();
  16. //start as many threads as possible to simulate problems easily
  17. For (int i = 0; i < ; i++)
  18. {
  19. //Each thread pair runs in object T, simulating a single case
  20. new Thread (t, "thread" + i). Start ();
  21. }
  22. }
  23. }

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: 10
[Thread 33] Gets the value of instance_i*2:20
[Thread 67] Gets the value of Instance_i: 4
[Thread 34] Gets the value of instance_i*2:8
[Thread 35] Gets the value of instance_i*2:20
[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:

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

Java code
  1. Public class Test implements Runnable
  2. {
  3. public Void Run ()
  4. {
  5. int local_i = 4;
  6. System.out.println ("[" + Thread.CurrentThread (). GetName ()
  7. + "] Gets the value of the local_i:" + local_i);
  8. Local_i = 10;
  9. System.out.println ("[" + Thread.CurrentThread (). GetName ()
  10. + "] Gets the value of the local_i*2:" + local_i * 2);
  11. }
  12. public static void Main (string[] args)
  13. {
  14. Test T = new test ();
  15. //start as many threads as possible to simulate problems easily
  16. For (int i = 0; i < ; i++)
  17. {
  18. //Each thread pair runs in object T, simulating a single case
  19. new Thread (t, "thread" + i). Start ();
  20. }
  21. }
  22. }

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{

public static 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 tmphere, each thread will create its own copy, so there is no wired security issues

Note that static variables, because they occupy a store during class loading, each thread is shared with this store, so if static variables are used in static methods, this will be a security issue for threads!

Summary: As long as the method contains static variables, it is non-thread-safe

From: http://blog.csdn.net/aaa1117a8w5s6d/article/details/8295527

(go) Static variables, instance variables, local variables for Java thread safety issues

Related Article

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.