java--Object Lock (reprint) __ Phase Summary

Source: Internet
Author: User
Tags finally block instance method

In concurrent environments, you can consider the use of lock mechanisms when resolving shared resource conflict issues.

1. Lock of Object

All objects automatically contain a single lock.

The JVM is responsible for tracking the number of times an object is locked. If an object is unlocked, its count becomes 0. When a task (thread) locks an object for the first time, the count changes to 1. The count increments whenever this same task (thread) Gets a lock on this object.

Only the task (thread) that obtains the lock first can continue to acquire multiple locks on the object.

Every time a task leaves a synchronized method, the Count decrements, and when the count is 0, the lock is completely freed, and other tasks can use the resource at this time.

2.synchronized Sync block

Synchronized has two forms:

Format 1:

Synchronized (any object) {

Access the critical section of a shared variable (program segment), also known as a synchronized code block

}

Format 2: Synchronization method. Precede the method with synchronized, such as:

Public synchronized void Add () {

Critical Zone

}

How the object lock associated with the shared variable is selected. That

Synchronized (any object) {

Critical Zone

}

1.synchronized locks a specific object, usually the object of a shared variable. The program segment enclosed in synchronized is the critical section that accesses the shared variable, that is, the synchronized code block. Because all the 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 serially and are no longer interleaved and executed concurrently, thus guaranteeing the synchronized The atomic nature of the code block operation. But the synchronized code block is interleaved with the synchronized code block of all threads and between the synchronized code block and the non-synchronized code block, Therefore, the atomic nature of the synchronized code block operation is logical, not physically not interrupted.

2. Each Java object has and has only one object lock. At any given moment, an object lock can only be owned by one thread. If two or more threads lock on the same object, their synchronized code blocks can be interleaved and executed concurrently.

3. All synchronized code blocks or methods can be invoked freely. If thread a obtains an object lock, calls the synchronized code block that requires the lock on the object, the other threads can still freely invoke all the synchronized methods and code

4. If thread a obtains the object lock of Object o, calling the synchronized code block or method of object o, thread A can still invoke any other synchronized code block or method that requires the lock of object o, because thread A has already obtained the object lock of object o. Thread A can also invoke a synchronized code block or method that requires a lock on another object K, which means that thread A also has object locks for object O and Object K.

5. The thread releases the acquired object lock only if a thread finishes executing the synchronized code block or method it calls, whether it is performed normally or thrown unexpectedly. Synchronized does not necessarily protect data. Programmers should carefully analyze, identify all critical areas in the program, and apply synchronized mechanisms to these critical areas. If there is one or more omissions, the data in the shared variable will produce an error

6. Shared variables in the critical section should be defined as private. Otherwise, methods of other classes may directly access and manipulate the shared variable, so that synchronized protection is meaningless. Therefore, the shared variable can only be accessed through the critical section. The object that is locked is usually this, which is usually formatted as: synchronized (this) {...}

7. It is important to ensure that all access and operations to shared variables are performed in the synchronized code block.

8. Usually shared variables are instance variables. If the shared variable in the critical section is a class variable, the problem is complicated because both the class method and the instance method can access the class variable. The synchronized lock must be an object and cannot be a class. The suggestion is that if the shared variable in the critical section is a class variable, then the class method should be used to access the operation of the class variable. This class method becomes a critical section, and the class method must be defined as a synchronized method. All instance methods that want to access the shared class variable should call the class method defined as synchronized. If the instance method must want to inside own code, does not pass the Synchronized class method to access the shared class variable, then may pass through synchronized (class name. classes) {... To access the class lock. Java, each class has a class object, this class object is actually an instance object of the Java.lang.Class, the so-called class lock is a lock of this class object. Note Class locks and object locks on instance objects of this class are both object locks, but different locks. All like synchronized (class name. Class ()) {= Sync code block} So lock class object (note: Not an instance object of the lock Class), where the synchronized code block, are serially executed, access or use class locks to carefully consider and weigh

9. When a thread enters a dead state, all object locks owned by the thread are freed.

3.Lock Object Lock

 

The Java SE5 introduces the Java.util.concurrent.lock class library, which is the second mechanism to resolve the mutex problem. Create a lock object with the Reentrantlock class to protect the critical section. The basic structure of the code block protected with Reentrantlock is as follows.

Private Lock Locker =new Reentrantlock ();

Locker.lock (); Lock

try{

...

}finally{

Locker.unlock (); Unlock

}

Lock () and unlock () must be used in support. You must ensure that the lock () corresponding to the unlock () is bound to be executed. Therefore, the unlock () must be placed in the finally block to ensure that the unlock () is bound to be executed, whether it is normal execution or exception-throwing.

The difference between synchronized and lock:

Lock locks are implemented through code, and synchronized is implemented at the JVM level

Synchronized if the method block throws an exception when the lock is locked, the JVM automatically releases the lock and does not cause the thread to deadlock because of an exception without releasing the lock. But lock will not be able to enjoy the JVM to bring automatic functionality, when the exception must be in the finally release the lock, otherwise it would cause deadlock.

In the case of resource competition is not very intense, occasionally there will be synchronization situations, synchronized is very appropriate. The reason is that the compiler usually optimizes the synchronize as much as possible, and the readability is very good, regardless of how many programmers use more than 5 thread packs to understand it.

Reentrantlock:
Reentrantlock provides a variety of synchronization, such as time-limited synchronization, can be interrupt synchronization (synchronized synchronization is not interrupt), and so on. In the case of less competitive resources, performance is slightly more than synchronized. But when the synchronization is very intense, the performance of synchronized can drop dozens of times times. And Reentrantlock can still remain normal.

Atomic:
Similar to the above, in a less intense situation, performance than synchronized slightly worse, and intense time, but also to maintain the normal. In the intense time, the atomic performance will be superior to reentrantlock about one times. But there is a drawback, that is, only one value can be synchronized, a piece of code can only appear a atomic variable, more than one synchronization is invalid. Because he can't sync between multiple atomic.

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.