Java Thread (i)

Source: Internet
Author: User

1. What is Java called thread safety? What do you mean, unsafe?

Thread synchronization means that when a program accesses a thread-safe method or statement, the other can no longer manipulate it, and must wait until the end of the visit to access the thread-safe method.
What is thread safety:
If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the values of the other variables are the same as expected,
is thread-safe.
Or, the interface provided by a class or program for a thread is an atomic operation or a switchover between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization.
Thread safety issues are caused by global variables and static variables.
In general, this global variable is thread-safe if there are only read operations for global variables and static variables in each thread, and if multiple threads are concurrently performing write operations, it is generally necessary to consider thread synchronization, which may affect thread safety.

A competing thread is unsafe, and a thread that does not exist is secure.

1. Thread safety (local variables)

     Public Static void test1 () {        int0;        I+ +;        System.  out . println (i);    }

  Because I is a local variable, there is no thread-safe issue. 100 threads are accessed at the same time, each with its own I, which does not cause thread safety issues.

2.servlet thread Unsafe (global variable)

 There is only one Servlet object, and I have only one, and there is a thread safety issue.

  Static member variables can also be thread-safe, static members execute when the ClassLoader loads, multiple objects share the same static member variable, and static member variables are not freed, and Java objects are automatically reclaimed by the JVM, so static member variables need to be used sparingly . For example, a static list collection, a server startup will be open for many years, the list will also exist for many years, if the object to add data to the list will cause a crash (list too large).

2.    talking about Java memory model
       different platforms, the memory model is not the same, but the JVM's memory model specification is unified. In fact, Java's multi-threaded concurrency problem will eventually be reflected in the Java memory model, so-called thread safety is nothing more than to control the multiple threads of a resource ordered access or modification. Summarize the Java memory model to solve two major problems: visibility and ordering. We all know that the computer has a cache, and the processor does not process the data every time it takes memory. The JVM defines its own memory model, shielding the underlying platform memory management details, and for Java developers, be clear on the JVM memory model, if the visibility and ordering of multithreading is addressed.
       So what is visibility? Communication between multiple threads cannot be communicated to each other, and they can only be communicated through shared variables. The Java Memory model (JMM) specifies that the JVM has primary memory and that the main memory is shared by multiple threads. When the new object is also allocated in the main memory, each thread has its own working memory, the working memory stores a copy of some objects of memory, of course, the size of the working memory of the thread is limited. When a thread is manipulating an object, the order of execution is as follows:
  (1) Copy variable from main memory to current working memory (read and load)
  (2) Execute code, change shared variable value (use and assign)
  (3) Refreshes main memory related content (store and write) with work-in-RAM data

The JVM specification defines the operation instructions for the thread to main memory: Read,load,use,assign,store,write. When a shared variable has a copy in the working memory of multiple threads, if a thread modifies the shared variable, the other thread should be able to see the modified value, which is the problem of multi-threaded visibility.
So, what is Order? A thread cannot reference a variable directly from the main memory, and if the thread does not have the variable in its working memory, it copies a copy from the main memory to the working memory, which is read-load, and the thread references the copy when it is finished. When the same thread references the field again, it is possible to retrieve a copy of the variable from main memory (Read-load-use), or it may refer directly to the original copy (use), meaning that the read,load,use order can be determined by the JVM implementation system.
A thread cannot assign a value directly to a field in the primary save, it assigns the value to a copy of the variable in the working memory (assign), and when done, the copy of the variable is synchronized to the primary store (Store-write), and as to when the past is synchronized, the system is determined by the JVM. There is this field, The field is assigned to the working memory from the main memory, the process is read-load, and after completion the thread references the copy of the variable, and when the same thread repeatedly assigns a value to the field, such as:

Java code

    1. for (int i=0;i<10;i++)
    2. a++;

for (int i=0;i<10;i++)

a++;


It is possible for a thread to assign only a copy in the working memory and synchronize to the primary store only after the last assignment, so the assign,store,weite order can be determined by the JVM implementation system. Suppose there is a shared variable x, thread a executes x=x+1. As you can see from the above description, x=x+1 is not an atomic operation, it is executed as follows:
1 read variable x copy to working memory from main memory
2 to X plus 1
3 Write the value of X plus 1 back to main memory
If another thread B executes the x=x-1, the following procedure is performed:
1 read variable x copy to working memory from main memory
2 to x minus 1.
3 Write the value of X minus 1 back to main memory
Then obviously, the value of the final x is unreliable. Assuming that X is now 10, thread a plus 1, and thread B minus 1, on the surface, it seems that the final x is still 10, but this happens in multithreaded situations:
1: Thread A reads x copy to working memory from main memory, x value is 10 in working RAM
2: Thread B reads x copy to working memory from main memory, x value is 10 in working RAM
3: Thread A will work in memory X plus 1, working memory x value is 11
4: Thread A submits x to main memory, X is 11 in main memory
5: Thread B minus 1 of x value in working memory, x value in working memory is 9
6: Thread B commits x to medium main memory, X is 9 in main memory
Similarly, X may be 11, if X is a bank account, thread a deposits, thread B deductions, obviously this is a serious problem, to solve this problem, it is necessary to ensure that thread A and thread B are executed sequentially, and that each thread executes an atomic operation that adds 1 or minus 1.

Synchronized Keywords
Java uses the Synchronized keyword as one of the guarantee methods for the execution order of multi-threaded concurrency environment. When a piece of code modifies a shared variable, this section of code becomes a mutex or a critical section, and in order to ensure the correctness of the shared variable, synchronized indicates the critical section. Typical usage is as follows:

Java code

    1. Synchronized (lock) {
    2. Critical section Code
    3. }

Synchronized (lock) {

Critical section Code

}

Theoretically, each object can be a lock, but when an object is locked, it should be shared by multiple threads, which makes sense, and in a concurrent environment, a non-shared object is meaningless as a lock . If there is such a code:

Java code

    1. public class threadtest{
    2. public void Test () {
    3. Object Lock=new object ();
    4. Synchronized (lock) {
    5. Do something
    6. }
    7. }
    8. }

public class threadtest{

public void Test () {

Object Lock=new object ();

Synchronized (lock) {

Do something

}

}

}


The lock variable is meaningless as a lock because it is not a shared object at all, and each thread comes in to execute Object Lock=new object (); Each thread has its own lock, there is no lock contention at all.
Each lock object has two queues, one is a ready queue, one is a blocking queue, the ready queue stores the thread that will acquire the lock, the blocking queue stores the blocked thread, and when a thread is awakened (notify), it goes into the ready queue and waits for the CPU to dispatch. When beginning thread A executes the Account.add method for the first time, the JVM checks to see if the ready queue of the lock object account is already thread-waiting, if any, indicates that the lock of the account is already occupied, and because it is the first run, the ready queue of the account is empty. So thread A gets the lock and executes the Account.add method. If it happens at this point, thread B is going to execute the Account.withdraw method because thread A has acquired a lock that has not been released, so thread B will go into the account's ready queue and wait until the lock is available to execute.
A thread executes the critical section code procedure as follows:
1 Obtaining a Sync lock
2 Empty working memory
3 copy variable copy from main memory to working RAM
4 Calculation of these variables
5 Write a variable from working memory back to main storage
6 Release Lock
It can be seen that synchronized not only guarantees the concurrent order of multithreading, but also ensures the memory visibility of multithreading.

Perhaps a lot of people are puzzled, say the JVM's memory model, how can pull the CPU up? In this regard, I think it is necessary to elaborate, so that many people can not see the shady. Leave the Java Virtual machine aside, we all know that now the computer, CPU in the calculation, not always read from the memory data, its data reading order priority is: Register-cache-memory. The thread consumes the CPU, the thread calculates the raw data from the memory, during the calculation, some data may be read frequently, the data is stored in registers and caches, when the thread is calculated, the cached data should be written back to memory when appropriate. When multiple threads read and write some memory data at the same time, there is a multi-threaded concurrency problem, involving three features: atomicity, ordering, visibility. In the Thread safety summary article, for ease of understanding, I call the unification of atomicity and order a "multi-threaded execution order". This is a problem for platforms that support multithreading, and languages that support multithreading on multithreaded platforms should provide a solution to the problem.

So, let's see JVM,JVM is a virtual computer, it will also face multi-threaded concurrency problems, Java programs run on the Java Virtual Machine platform, Java programmers can not directly control the underlying thread to register cache memory synchronization between, then Java from the syntax level, Developers should be given a solution, such as synchronized, volatile, locking mechanisms (such as synchronization blocks, ready queues, blocking queues), and so on. These schemes are only grammatical, but we need to understand them in nature, not just to know that a synchronized can guarantee that the synchronization will be done. What I'm talking about here is the JVM's memory model, which is dynamic, multi-threaded concurrency, followed by JSL's "working memory" argument, just don't want to involve too much of the underlying details, because "Thread safety summary" This article is intended to illustrate how to understand Java thread synchronization from a grammatical level, and to know the usage scenarios for each keyword.

Today, someone asked me, the Java thread is not a stack it? is the stack not working memory? Working memory These four words to be described in a specific scenario, to reflect its specific meaning, in the description of the JVM thread synchronization, working memory refers to the register and tell the cache abstract description, specifically, please refer to JLS. It's all about dynamic memory models, even beyond the scope of the JVM, so how does the JVM's memory static storage be divided? Today, I was asked if the JVM's memory model had no Eden area? I don't see you mentioning it. I told him that this is two angles to see, even two different ranges, dynamic thread-synchronous memory models that cover the CPU, registers, caches, and memory; the JVM's static internal storage model is just a physical partition of memory, confined to memory and confined to the JVM's memory. Those lines stacks, the Eden Zone is only in JVM memory.

Tell me about the JVM line stacks and the Eden area where my friend repeatedly struggled with me. The memory of the JVM is divided into a lot of areas:

1. Program Counter
Each Java thread has a program counter that holds the instructions that the program executes to the current method.
2. Wire Stacks
When each method of a thread is executed, a frame is created at the same time to store information such as local variable tables, operation stacks, dynamic links, method exits, and so on. The call to completion of each method means that a frame is loaded into the stack in the VM stack. If the thread requests a stack depth greater than the virtual machine allows, the Stackoverflowerror exception is thrown, and if the VM stack can be dynamically extended (a fixed-length VM stack is allowed in the VM spec), The OutOfMemoryError exception is thrown when the extension cannot request enough memory.
3. Local method Stack
4. Heap

The stack for each thread is private to the thread, and the heap is shared by all threads. When we new an object, the object is assigned to the heap. But the heap, is not a simple concept, the heap is divided into a lot of areas, why the heap is divided into so many areas, this is for the JVM's memory garbage collection, it seems that the farther away from the garbage collection, the current JVM GC is collected by generation, the heap area is broadly divided into three chunks: the new generation, the old generation, Permanent generation (virtual), the new generation is divided into the Eden area, S0 District, S1 district. When you create a new object, the basic small object, the short life of the object will be placed in the new generation of Eden, when Eden is full, there is a small range of GC (minor GC), the entire Cenozoic full, there will be a large range of GC (major GC), the new generation of some of the objects transferred to the old generation.
5. Method Area
In fact, the permanent generation (Permanent Generation), the method area contains the structure information of each class, including constant pool, field description, method description, and so on. The restrictions on this area in the VM space description are very loose, with the exception of the Java heap, which does not require contiguous memory, can optionally be fixed size or extensible, and can even choose not to implement garbage collection. Relatively speaking, the garbage collection behavior in this area is relatively small occurrence, but not some of the description of the permanent generation will not occur GC (at least for the current mainstream commercial JVM implementation is so), here the GC is mainly for the constant pool of recycling and unloading classes, although the recovery of "score" is generally less than satisfactory, Especially class unloading, the conditions are quite harsh.
6. Constant Pool
class file In addition to the class version, fields, methods, interfaces and other information such as descriptions, there is also a constant table (Constant_pool table), for the compilation of the known constants, which will be loaded in the class load into the method area (permanent generation) storage. However, the Java language does not require constants to enter the method area constant pool only if the content of the const table of the class is pre-compiled, and the new content can be put into Chang (the most typical String.intern () method) during the run time.

3. An example of a thread insecurity

When we look at the JDK API, we always find some class descriptions that say thread-safe or thread-insecure, such as StringBuilder, that " StringBuilder it is not safe to use instances for multiple threads." If such synchronization is required, it is recommended StringBuffer . ", then manually create a thread-unsafe class, and then use this class in multi-threading to see what the effect is.

Count.java:

 Public class Count {      privateint  num;        Public void count () {          for (int i = 1; I <=; i++) {              += i;          }           + "-" + num);      }  

The Count method in this class is to calculate the sum of 1 to 10 and output the current thread name and sum, and we expect that each thread will output 55.

Threadtest.java:

  Public classThreadTest { Public Static voidMain (string[] args) {Runnable Runnable=NewRunnable () {count Count=NewCount ();  Public voidrun () {count.count ();          }          };  for(inti = 0; I < 10; i++) {              NewThread (runnable). Start (); }      }  } 

This launches 10 threads and looks at the output:

thread-0-55  thread-1-110  thread-2-165  thread-4-220  thread- 5-275  thread-6-330  thread-3-385  thread-7-440  Thread -8-495  Thread-9-550

Only the results of the Thread-0 thread output are what we expect, and the output is cumulative each time, here the reasons for the accumulation of the post will be explained, then to get the results we expect, there are several solutions:

1. Change num in count to the local variable of the Count method ( Local variables do not have thread safety issues )

 Public class Count {      publicvoid  count () {          int num = 0;            for (int i = 1; I <=; i++) {              + = i;          }           + "-" + num);      }  }

2. Take the thread class member variable to the Run method, when the count reference is a local variable within the thread;

  Public classThreadTest4 { Public Static voidMain (string[] args) {Runnable Runnable=NewRunnable () { Public voidRun () {count Count=NewCount ();              Count.count ();          }          };  for(inti = 0; I < 10; i++) {              NewThread (runnable). Start (); }      }  } 

3. Each time a thread is started with a different thread class, it is not recommended.

The above tests, we found that the existence of member variables of the class used for multi-threading is unsafe, unsafe reflected in this member variable may occur non-atomic operations , and variables are defined in the method that the local variables are thread-safe. When using STRUTS1, it is not recommended to create member variables, because action is a singleton, and if you create a member variable, there is a risk of thread insecurity, and struts2 is creating an action for each request, regardless of the thread safety issue. Therefore, in the daily development, it is usually necessary to consider the member variables or global variables in the multi-threaded environment, whether it will cause some problems.

Java Thread (i)

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.