1, five ways 1.1 synchronized synchronization method
Use the Synchronized keyword decoration method. Each Java object has a built-in lock that, when modified with this keyword, protects the entire method. Before calling this method, you need to get the built-in lock, otherwise it will be in a blocked state.
such as: public synchronized void Save () {}
Note: When the Synchronized keyword modifies a static method, the entire class is locked
1.2 Synchronized Synchronous code block
That is, a statement block that has the synchronized keyword modifier. Statement blocks that are decorated with this keyword are automatically added with built-in locks for synchronization
such as: synchronized (object) {}
Note: Synchronization is a high-overhead operation, so you should minimize the content of synchronization. It is usually not necessary to synchronize the entire method, using the synchronized code block to synchronize the key code.
1.3 volatile
- The volatile keyword provides a lock-free mechanism for accessing domain variables.
- Using the volatile modifier domain is equivalent to telling the virtual machine that the domain might be updated by another thread.
- So each time the domain is used, it is recalculated instead of using the value in the Register
- Volatile does not provide any atomic manipulation, nor can it be used to modify a final type of variable
Note: To synchronize access to a shared variable, the result of the last write operation is certainly visible to the next read operation. (After writing the value of the volatile variable, the contents of the CPU cache are written back to memory, and when the volatile variable is read, the corresponding contents in the CPU cache are invalidated, re-read from main memory), volatile does not use locks, Performance is better than synchronized keywords.
1.4 Re-entry lock Reentrantlock
A. Concept and use
A java.util.concurrent package has been added to support synchronization in JavaSE5.0. The Reentrantlock class is a re-entrant, mutex, and lock interface that implements the same basic behavior and semantics as using the Synchronized method, and extends its capabilities
Common methods of the Reentrantlock class are:
- Reentrantlock (): Create an Reentrantlock instance
- Lock (): Get lock
- Unlock (): Release lock
Note: Reentrantlock () also has a construction method that can create a fair lock, but is not recommended because it can significantly reduce the efficiency of program operation
B. About the lock object and synchronized keyword selection:
- It is best to use a mechanism provided by the Java.util.concurrent package to help users handle all lock-related code.
- If the Synchronized keyword satisfies the user's needs, use synchronized because it simplifies the code
- If you need more advanced features, use the Reentrantlock class, you should pay attention to release the lock in time, otherwise there will be deadlock, usually in the finally code release lock
1.5 Local Variables
If you use threadlocal to manage variables, each thread that uses the variable gets a copy of the variable, and the replicas are independent of each other so that each thread can modify its own copy of the variable without affecting other threads.
Common methods of Threadlocal class
- ThreadLocal (): Create a thread-local variable
- Get (): Returns the value in the current thread copy of this thread's local variable
- InitialValue (): Returns the "initial value" of the current thread for this thread's local variables
- Set (T value): Sets the value in the current thread copy of this thread's local variable to value
Note: threadlocal and synchronization mechanism
- The threadlocal and synchronization mechanisms are all designed to solve the problem of access violation of the same variable in multi-threading.
- The former adopts the method of "space Change Time", the latter adopts the way of "time changing Space".
2. Four ways of synchronized2.1
- Method is declared, the thread obtains a member lock.
- For a block of code, synchronized is followed by parentheses, in parentheses is the variable, and the thread obtains the member lock.
- Synchronized is an object in parentheses, at which point the thread obtains an object lock.
- Synchronized is the class in parentheses, at which point the thread obtains an object lock.
2.2 Use Features
- The synchronized key is only used to provide mutually exclusive access to Java shared resources in a multithreaded environment. It guarantees synchronization problems for multiple threads that use the same lock,
- Synchronized key can only be used in the synchronized method or synchronized block, the variable can not be synchronized operation
- When a thread enters synchronized, it must obtain a corresponding lock, and when it leaves, it releases the corresponding lock. The lock will be released when the thread completes the synchronization or if an error or exception occurs.
- When Java thread makes a syncrhonized Java method, it asks for an object-level lock, and when it enters the static synchronized method, it needs to obtain a class-level lock.
- The Java synchronized keyword can be re-entered.
- Java throws a NullPointerException exception if the Java synchronized block synchronizes an object that is null.
- Synchronized synchronization can only be performed on the same JVM.
- Using synchronized can cause performance to fall.
- Java synchronized block is superior to synchronized method
- After Java5, the variables that use violate are atomic.
- Synchronized cannot be used in constructors, it can cause programming errors.
- Synchronized cannot be used on a variable
- Java class Libraries calendar and Simpledataformat are not thread-safe, so additional synchronization mechanisms are required.
http://blog.csdn.net/php_boy/article/details/6778672
3. Volatile
Ensure that in-memory shared variables are in the most recently modified state when multithreaded threads are concurrently operating
3.1 Two-tier semantics of volatile keywords
Once a shared variable (a member variable of a class, a static member variable of a class) is modified by volatile, then there are two layers of semantics:
- The visibility of this variable is ensured by a thread that modifies the value of a variable, which is immediately visible to other threads.
- command reordering is prohibited.
What is Order reordering, in general, the processor may optimize the input code in order to improve the efficiency of the program, and it does not guarantee that the execution order of each statement in the program is consistent with the order in the code, but that it ensures that the results of the final execution of the program and the execution of the code order are consistent.
Command reordering does not affect the execution of a single thread, but it can affect the correctness of concurrent execution of threads.
3.2 Usage Scenarios
The Synchronized keyword is to prevent multiple threads from executing a piece of code at the same time, which can affect program execution efficiency, while the volatile keyword has better performance than synchronized in some cases. Note, however, that the volatile keyword cannot replace the synchronized keyword because the volatile keyword does not guarantee the atomicity of the operation. In general, the following 2 conditions are required to use volatile:
- A write to a variable does not depend on the current value
- The variable is not included in the invariant with other variables
In fact, these conditions indicate that these valid values that can be written to a volatile variable are independent of the state of any program, including the current state of the variable.
In fact, my understanding is that the above 2 conditions need to ensure that the operation is atomic, so that programs that use the volatile keyword can execute correctly when concurrency occurs.
4, ThreadLocal4.1 use characteristics
Threadlocal mainly solves the problem that the data in multi-threading is inconsistent with concurrency.
Threadlocal provides a copy of the data that is accessed concurrently in each thread and runs the business through the access replica, which results in memory consumption, which greatly reduces the performance cost of thread synchronization and reduces the complexity of thread concurrency control.
Threadlocal cannot use atomic types, only object types. Threadlocal is much simpler to use than synchronized.
4.2 Use steps
- In a multithreaded class (such as the Threaddemo Class), create a Threadlocal object threadxxx, which is used to hold object XXX between threads that need to be treated in isolation.
- In the Threaddemo class, create a Method getxxx () that gets the data to be quarantined, and in the method it is judged that if the Threadlocal object is null, a new () object should be created to isolate the access type and cast to the type to be applied.
- In the Run () method of the Threaddemo class, the data to be manipulated is obtained by means of the getxxx () method, which ensures that each thread corresponds to a data object, which is manipulated at any time.
5. Volatile and synchronized
- The volatile nature is to tell the JVM that the value of the current variable in the register is indeterminate and needs to be read from main memory, while the synchronized is locking the current variable, and other threads are blocked only if the variable is accessible to the thread.
- Volatile can only be used at variable levels; synchronized can be used in variables, methods.
- Volatile can only implement variable visibility, but does not have atomic characteristics, while synchronized can guarantee the change of the visibility of variables and atomicity.
- Volatile does not cause a thread to block, while synchronized can cause a thread to block.
- Volatile tagged variables are not optimized by the compiler, while synchronized tagged variables can be optimized by the compiler.
Summary: The volatile nature is to tell the JVM that the value of the current variable in the register is indeterminate and needs to be read from main memory. Some of the effects of synchronized can be achieved, but when the n=n+1,n++ and so on, the volatile keyword will be invalidated, unable to play the same role as synchronized thread synchronization effect.
6. Similarities and differences between Reentrantlock and synchronized6.1
Same as: Reentrantlock provides similar functionality and memory semantics for synchronized.
Different:
- Reentrantlock functionality is more comprehensive, such as time lock waiting, can interrupt lock wait, lock vote, etc., so more extensibility. In the case of multiple condition variables and highly competitive locks, it is more appropriate to use Reentrantlock, Reentrantlock also provides condition, more flexibility for thread wait and wake operations, and a reentrantlock can have multiple condition instances , so it's more scalable.
- Reentrantlock must release the lock in Finally, otherwise the result is very serious , the coding angle to use synchronized more simple, not easy to omit or error.
- Reentrantlock's performance is better than synchronized.
- Reentrantlock provides a polling lock request , he can try to get the lock, if successful then continue processing, get unsuccessful, can wait for the next run time processing , so it is not easy to create a deadlock, and Synchronized is more likely to generate deadlocks once the lock request is either successful or blocked .
6.2 Use Features:
- Some methods of lock can determine how long to attempt to acquire a lock and throw an exception if it is not obtained, thus reducing the likelihood of deadlocks to some extent.
- If the lock is occupied by another thread, synchronized will only wait, and it is easy to sequence the deadlock
- Synchronized, the scope of the lock is the entire method or the synchronized block, and lock is a method call that can be more flexible across methods
- Easy to test, unit test, you can simulate lock, determine whether to obtain a lock, and synchronized will not be able to
Where is 6.3 reentrantlock stronger than synchronized?
Simply put:
1, Reentrantlock can achieve fair lock
1 Public Reentrantlock (boolean Fair) { 2 newnew nonfairsync (); 3 }
The so-called fair lock is to see if the order of the locks is consistent with the order of the time of the lock application
2, Reentrantlock support interrupt processing
1 public final void acquireinterruptibly (int Arg) Span style= "color: #0000ff;" >throws Interruptedexception { 2 if (thread.interrupted ()) throw New Interruptedexception (); 4 if (!tryacquire (ARG)) 5 Doacquireinterrupt ibly (ARG); }
This means that the thread holding the lock is not released, and the waiting thread can give up waiting.
3, Reentrantlock can be used in conjunction with the condition
1 Public Booleanhaswaiters (Condition Condition) {2 if(Condition = =NULL)3 Throw Newnullpointerexception ();4 if(! (conditioninstanceofabstractqueuedsynchronizer.conditionobject))5 Throw NewIllegalArgumentException ("Not owner");6 returnsync.haswaiters ((abstractqueuedsynchronizer.conditionobject) condition);7 }8 9 Public intgetwaitqueuelength (Condition Condition) {Ten if(Condition = =NULL) One Throw Newnullpointerexception (); A if(! (conditioninstanceofabstractqueuedsynchronizer.conditionobject)) - Throw NewIllegalArgumentException ("Not owner"); - returnsync.getwaitqueuelength ((abstractqueuedsynchronizer.conditionobject) condition); the}7, threadlocal and synchronized:
- Synchronized is the mechanism by which a lock is used so that a variable or block of code can be accessed by only one thread at a time. Instead, Threadlocal provides a copy of the variable for each thread, so that each thread accesses the same object at a certain time, isolating data sharing from multiple threads. Synchronized, in contrast, is used to gain data sharing when communicating between multiple threads.
- Synchronized is used for data sharing between threads, while threadlocal is used for data isolation between threads. Of course threadlocal is not a substitute for synchronized, they deal with different problem domains. Synchronized is used to implement synchronization mechanisms and is more complex than threadlocal.
Http://www.2cto.com/kf/201408/324061.html
Http://www.cnblogs.com/dolphin0520/p/3920373.html
http://my.oschina.net/songhongxu/blog/197925
Multithreaded programming--Thread synchronization method