First, preface
Recently in the work of a static method, with colleagues to communicate, was a question to ask, only strange foundation not solid ...
The question is roughly this, "in a multithreaded environment, will the local variables in the static method be contaminated by other threads?" ”;
I was thinking: The method of the local variables at run time, is present in the Java stack, the method runs the end, the local variables are all light, theoretically single-threaded word is not a problem, I do not know, because it is not clear in the Java memory model, a thread corresponding to a stack, Or a stack shared by multiple threads ...
In fact, if you know that each thread has its own Java stack, the problem is very clear, will not be contaminated by other threads;
Of course, the problem does not stop here, the problem has been exposed to this aspect is relatively weak, so intends to the Java memory model and multithreading concurrency problems to make a small summary;
Second, the memory model in Java
When the program runs, the memory is mainly composed of the following parts:
- heap : All threads share a heap, and all are stored in new objects, and collected by the garbage collector;
- method Area : All threads share a method area; The contents are a bit miscellaneous and can be thought of as other things in addition to heaps and stacks (such as class information, static variables, constants, code, etc.); Java Virtual Machine specification specifies that garbage collection of method areas is not possible, Mainly see the implementation of specific virtual machines, such as can be recycled some obsolete constants and useless classes;
- Program Counter : Also called the PC, place the address of the unit where the next instruction is stored;
- Java stack : Each thread has its own Java stack, the store is generally a method of local variables, methods, such as export information, the method calls the process of automatic stack out, PS: Stack space size is limited;
- Local method Stack : Similar to the Java stack, the difference is that the object used is different, the local method stack is used for the native method, the Java stack is used for Java mode;
Attached to a picture, the Java Virtual machine will have a whole understanding;
Third, multi-threaded access to shared memory situation
When multiple threads execute the same method,
When an unexpected result may occur:
Multiple threads share an area of memory and operate on it without any protection;
When you might get the right result:
Does not use shared memory, each thread memory space is independent of each other;
Multithreading shares a chunk of memory, but locking access to the shared area;
Iv. Description of the case
Situation one (multiple threads share a chunk of memory and operate on it without any protection):
Write a class with a static method, sum, the method uses a static global s (multiple threads can access simultaneously):
Packagecom.pichen.java.static_; Public classStatictest {Private Static ints = 0; Public Static intSumintN) {s= 0; for(inti = 0; I <= N; i++) {s+=i; Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } } returns; }}
Write a thread that calls the static method above:
Packagecom.pichen.java.static_; Public classThreadCountImplementsrunnable{@Override Public voidrun () { while(true) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +statictest.sum (100)); Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } } }}
Write a main function, starting three threads, observing the results of the operation, basically is wrong:
Packagecom.pichen.java.static_; Public classMain { Public Static voidMain (string[] args) {threadcount T1=NewThreadCount (); NewThread (T1). Start (); ThreadCount T2=NewThreadCount (); NewThread (T2). Start (); threadcount T3=NewThreadCount (); NewThread (T3). Start (); }}
The running result does not match the expected:
thread-0:13968thread-1:13968thread-2:13968thread-0:13033thread-1:13033thread-2:13033thread-1:14725thread-0 : 14725
Cause: Multiple threads are simultaneously operating on the static global variable s;
PS: Here is the static global variable s, in fact, there are a number of situations will cause the result of the problem, such as in the Main method of the new object, the new object is stored in the heap, multiple threads are shared, at this time if the multi-threaded simultaneous operation of the object, it is possible to produce incorrect results;
Scenario two (do not use shared memory, each thread memory space is independent of each other):
To modify the static sum method, use the local variable s, as follows:
Packagecom.pichen.java.static_; Public classStatictest {Private Static ints = 0; Public Static intSumintN) { ints = 0; for(inti = 0; I <= N; i++) {s+=i; Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } } returns; }}
Run the program with the correct results:
thread-1:5050thread-0:5050thread-2:5050thread-0:5050thread-2:5050thread-1:5050thread-0:5050
Scenario three (multithreading shares a chunk of memory, but locking access to this shared area):
Packagecom.pichen.java.static_; Public classStatictest {Private Static ints = 0; Public synchronized Static intSumintN) {s= 0; for(inti = 0; I <= N; i++) {s+=i; Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } } returns; }
Run the program with the correct results:
thread-1:5050thread-0:5050thread-2:5050thread-0:5050thread-2:5050thread-1:5050thread-0:5050
Reprint Address: Http://www.cnblogs.com/chenpi/p/5159558.html thank the original author
About static methods in Java, concurrency problems, and the Java Runtime memory model