In a concurrent environment, you can consider using the lock mechanism to resolve shared resource conflicts.1.Object lockAll objects automatically contain a single lock. JVM is responsible for tracking the number of times an object is locked. If an object is unlocked, its count is 0. When the task (thread) locks the object for the first time, the Count changes to 1. Every time this same task (thread) gets a lock on this object, the Count increases progressively. Only the task (thread) that first obtains the lock can continue to obtain multiple locks on the object. Every time a task leaves a synchronized method, the Count decreases. When the count is 0, the lock is completely released, and other tasks can use this resource.2. synchronizedSynchronization BlockSynchronized has two formats: Format 1: synchronized (any object) {// access the critical section (program segment) of shared variables, also known as Synchronous Code block} Format 2: synchronous method. Add synchronized before the method, for example, public synchronized void add () {// critical section}. How do I select the object lock associated with the shared variable? That is, synchronized (any object) {// critical section} 1. synchronized is a specific object, usually an object that shares variables. The program segment enclosed by synchronized is the critical section for accessing the shared variable, that is, the synchronized code block. Because all threads that lock the same object are mutually exclusive on the synchronized code block, that is to say, the synchronized code blocks of these threads are executed in a serial manner and are no longer interspersed with each other for concurrent execution, therefore, the atomicity of synchronized code block operations is ensured. However, the synchronized code block and the non-synchronized code block of all threads and the non-synchronized and non-synchronized code blocks are interspersed with each other for concurrent execution. Therefore, the atomicity of synchronized code block operations is logical, instead of being physically interrupted. 2. Each Java object has only one object lock. An object lock can only be owned by one thread at any time. If two or more threads lock different objects, their synchronized code blocks can be interspersed with each other for concurrent execution. 3. All non-synchronized code blocks or methods can be freely called. For example, if thread A acquires the object lock and calls the synchronized code block that requires the object lock, other threads can still freely call all non-synchronized methods and code 4. if thread A acquires the object lock of object O and calls the synchronized code block or method of object O, thread A can still call any other synchronized code block or method that requires the Lock of object O, this is because thread A has obtained the object lock of object O. Thread A can call the synchronized code block or method that requires the Lock of another object K at the same time, which means that thread A owns the object lock of object O and object K at the same time. 5. Only when a thread executes the synchronized code block or method it calls, whether it is normal execution or exception throw, the thread will release the acquired object lock. Synchronized does not necessarily protect data. Programmers should carefully analyze and identify all critical sections in the program, and apply the synchronized mechanism to these critical sections. If one or more omissions exist, the data in the shared variables may produce errors. 6. The shared variables in the critical section should be defined as private. Otherwise, the methods of other classes may directly access and operate on the shared variable, so that the protection of synchronized becomes meaningless. Therefore, shared variables can only be accessed through the critical section. Therefore, the locked object is usually this, that is, the common format is synchronized (this ){...} 7. Make sure that all access and operations to shared variables are performed in the synchronized code block. 8. Generally, shared variables are instance variables. If the shared variable in the critical section is a class variable, the problem is complicated because the class and instance methods can both be class variables. Synchronized must be an object and cannot be a class. It is recommended that if the shared variable in the critical section is a class variable, you should use the class method to access this class variable. This class method becomes a critical section and must be defined as the synchronized method. All instance methods to access this shared class variable should be called the class method defined as synchronized. If the instance method must be inside your own code and you do not use the synchronized class method to access Shared class variables, you can use synchronized (class name. class ){... Class lock. In Java, each Class has a Class object, which is actually an instance object of java. lang. Class. The so-called Class lock is a lock of this Class object. Note that although the Object locks of the Instance objects of the class and the class are both Object locks, they are two different locks. All synchronized (class name. class () {= Synchronous Code block} locks the class Object (Note: it is not an Instance Object of the lock class), where the synchronized code block is executed in serial mode, to access or use a class lock, you must carefully consider and weigh 9. when a thread enters the dead state, all Object locks owned by the thread are released.3. LockObject lock Java SE5 introduces the java. util. concurrent. lock class library, which is the second mechanism to solve the mutex problem. Use the ReentrantLock class to create a Lock object to protect the critical section. The basic structure of the code block protected by ReentrantLock is as follows. Private Lock locker = new ReentrantLock (); locker. lock (); // Lock try {...} Finally {locker. unlock (); // unlock} lock () and unlock () must be used together. Make sure that the unlock () corresponding to lock () is executed. Therefore, you must put the unlock () in the finally block to ensure that the unlock () will be executed whether it is normal execution or thrown exceptions. The difference between synchronized and lock: the Lock is implemented by code, while synchronized is implemented at the JVM level. If an exception occurs during the lock, the JVM Automatically releases the lock and does not cause a thread deadlock because of exceptions. However, if you use the Lock function, you will not be able to use the automatic functions provided by JVM. If an exception occurs, you must release the Lock in finally; otherwise, a deadlock will occur. Synchronized is suitable for occasional synchronization when resource competition is not fierce. The reason is that the compilation program usually optimizes synchronize as much as possible. In addition, the program is very readable and can be understood by programmers who have never used 5.0 multi-threaded packages.
ReentrantLock:
ReentrantLock provides various types of synchronization. For example, synchronization with limited time can be synchronized by Interrupt (synchronization of synchronized cannot Interrupt. When resources are not highly competitive, the performance is slightly worse than synchronized. However, when synchronization is very intense, the performance of synchronized can suddenly be reduced by dozens of times. However, ReentrantLock can remain normal.
Atomic:
Similar to the above, the performance is slightly inferior to synchronized in less intense cases, while it can maintain normal performance in intense cases. In severe cases, Atomic performance is about twice as good as ReentrantLock. However, one drawback is that only one value can be synchronized. Only one Atomic variable can appear in a piece of code, and more than one synchronization is invalid. Because it cannot be synchronized between multiple atomics.