Recently made a pen test, encountered a lot of thread safety issues, such as:
What is the difference between synchronized and volatile?
What is the difference between StringBuilder and StringBuffer?
What is the difference between HashMap and Hashtable? and so on ...
The answers to these questions relate to thread safety issues. First of all, there is a concept of thread safety, how to call thread safety.
thread safety and thread insecurity:
thread Safety refers to the concurrent execution of multiple threads, when a thread accesses a data of that class, through the locking mechanism, to protect the data until the current thread is finished reading, release the lock, other threads can continue to use, we think this is thread-safe.
Wired thread security, natural on the thread is unsafe, threads unsafe refers to, when multiple threads concurrently execute, the data is not protected, there may be multiple threads to modify or use some data, resulting in incorrect data, that is, dirty data.
After understanding the basic concepts, the next step is to refer to a great God describing thread security from the Java memory model and thread synchronization mechanisms.
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.
Visibility: Multiple threads cannot communicate data to each other, and communication between them can only be done 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) Copying variables from main memory to current working RAM (read and load)
(2) Execute code, change shared variable value (use and assign)
(3) Refresh main memory related content (store and 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.
ordering: A thread cannot reference a variable directly from main memory, and if the thread does not have the variable in its working memory, a copy is copied from the main memory to the working memory, and the thread references the copy when 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 Assign, it assigns the value to a copy of the variable in the working memory (*. *), and the copy of the variable is synchronized to the primary store (Store-write) when it is completed, and the system is determined by the JVM when it is synchronized. There is this field, The field is assigned to the working memory from the main memory, and the process is read-load, and the thread references the variable copy after completion.
For Example 1, an existing variable x=10,a thread performs x=x+1 operations, B threads perform x=x-1 operations, when both threads run simultaneously, the value of x is indeterminate, possibly 9, or 11, which is the order of multithreading concurrency execution is unpredictable, So for thread safety, ensure that the A and B threads are executed in an orderly manner, and that the operations performed must be atomic operations .
Atomic manipulation: When you access a shared resource in multiple threads, you can ensure that all other processes (threads) do not access the same resources at the same time. Atomic operations (atomic operation) are not required synchronized, which is the cliché of Java multithreaded programming. Atomic operations are operations that are not interrupted by the thread-scheduling mechanism, which, once started, runs until the end without any context switch (switching to another thread).
So how do you ensure the order and visibility of thread execution?
Synchronized Keywords
The synchronized keyword solves the problem of ordering and visibility, which guarantees that multiple threads are mutually exclusive, and when a piece of code modifies a shared variable, the piece of code becomes a mutex or a critical section, in order to guarantee the correctness of the shared variable, Synchronized marked the critical section.
Common usage:
Java code
synchronized (lock) {critical section code} // For example: Public synchronized void method () {} Public Static synchronized void method () {}
Regardless of whether the Synchronized keyword is added to a method or an object, the object is taken as a lock, in theory each object can be a lock.
In the case of public synchronized void method (), the lock is the object in which the method resides. Similarly, if the method is public static synchronized void method (), then the lock is the class in which the method resides.
Synchronized keyword has two kinds of lock objects, one is Object lock, the other is to lock the class, lock the class, then the class lock on all objects in the class function, and the object lock is only for a specified object of the class lock, Other objects of this class can still use the Synchronized method that has been locked for the previous object.
For example: The station only one ticket, a salesman and b salesman at the same time the ticket, the implementation of public synchronized void Sell () method, then the results will appear, the remaining votes of (-1), this is the object lock caused by the problem, other objects can still use this method;
When the Sell method is added to the static, the lock object is this class, for a Salesman and b salesman, should be in order to operate the business, so that there will not be a negative number of votes for the light card un.
When an object is a lock, it makes sense to be shared by multiple threads. This also comes to a conclusion: non-threaded security! = Not secure.
For example, ArrayList is not thread-safe, but does not mean that the multi-threaded case is not ArrayList, if you each of the threads are new ArrayList object, that is, the object is unshared, there is no resource competition between the threads, There is no security problem with many threads executing.
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, it goes to the ready queue and waits for the CPU to dispatch.
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.
The producer/consumer pattern is a typical synchronous lock problem, in which the multithreading process, in addition to being mutually exclusive, often occurs when the threads collaborate with each other.
For example, a robot is responsible for making a car, making a car, and putting it in a warehouse where only one car can be placed at a time.
(1) At first, a robot was run, the implementation of the car making method, built the car in the warehouse, not immediately shut down (release of the lock), but rather wake up (notify) ready to work (blocking queue) b robot, and then work (into the blocking queue)
(2) b robot to obtain a synchronous lock, to work, began to get the car shipped out of the warehouse to sell, the car shipped out, it did not immediately slipped, but woke up just off the a robot to continue to build the car (naked exploitation, I also want to sell cars).
(3) A robot found the warehouse of the car was carried away, received the task can only continue to build the car, build a good car to call the B robot back.
(4) b robot sells cars, wakes a robot to build cars.
。。。。。。
It can be seen that in the role of synchronous lock, build cars, sell cars, build cars, sell cars can be carried out in an orderly manner, very happy.
The next thing to say is another keyword:volatile
volatile keyword
Volatile is also a Java synchronization method, but compared with synchronized lock, slightly weaker point, it can only guarantee the visibility of multi-threaded execution, can not guarantee the order.
The principle is that you do not need to copy a copy from the main memory to the working memory, but instead directly modify the data in the main memory so that other threads can immediately see the data modification. Therefore, the use of volatile the scope of the arm synchronized small, often used for direct assignment, such as Example 1 of the case is not applicable.
Finally, it should be noted that the synchronized lock is good, but it can not be used more, it will affect the efficiency of execution, the blocking queue of the thread will continue to try to acquire locks, consumption performance. More about synchronized and volatile usage here is not to start to say, you can Baidu a detailed usage.
This article refers to the http://www.iteye.com/topic/806990, it is easier to understand, thank the great God.
Java Thread Safety