Synchronous locks in concurrency (synchronized)

Source: Internet
Author: User
Tags mutex object object thread class
This article is reproduced from: http://www.cnblogs.com/danbing/p/5319820.html Why should I use a sync lock? In "Thinking in Java," it is said that for concurrent work, you need some way to prevent two tasks from accessing the same resource (in fact, sharing a resource competition). The way to prevent this conflict is to lock the resource when it is used by a task.      The first task that accesses a resource must lock the resource so that the other task cannot access it until it is unlocked, and when it is unlocked, another task can lock and use it. Basically all concurrency patterns are used to serialize access to shared resources when solving thread-conflict problems. This means that only one task is allowed to access a shared resource at a given moment, usually by adding a lock statement to the code, which produces a mutually exclusive effect called a mutex (mutex). The realization principle of synchronous lock. All objects automatically contain a single lock (monitor), which is locked when any synchronized method is invoked on the object.   For a particular object, all of its synchronized methods share the same lock, which can be used to prevent multiple tasks from simultaneously accessing the encoded object memory. To share the same lock for all synchronized methods for a particular object, I would like to focus on: 1. When two concurrent threads access the synchronized (this) synchronized code block in the same object, only one thread can be executed at a time.   Another thread must wait until the current thread finishes executing the code block before executing the code block.   2. When a thread accesses a synchronized (this) synchronization code block of object, access to all other synchronized (this) synchronized code blocks in object is blocked by other threads. 3. When a thread accesses a synchronized (this) synchronization code block of object, it obtains the object lock of the objects. As a result, access to all of the synchronization code portions of the object object by other threads is temporarily blocked

Here's the point. A task can get a lock on an object multiple times. This can happen if a method invokes the second method on the same object, which calls another method on the same object. The JVM is responsible for tracking the number of times an object is locked, and if an object is unlocked, the count becomes 0. The count changes to 1 when the task is locked for the first time. Whenever this same task gets a lock on this object, the count increments. Obviously, only the task that first acquired the lock can continue to acquire more than one lock. Whenever 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 this resource.

when to use a sync lock.

  Brian Sync rule: If you are writing a variable, it may next be read by another thread, or you are reading a variable that was last written by another thread, then you must use synchronization, and the read-write thread must synchronize with the same monitor lock.   Note: Each method that accesses a critical shared resource must be synchronized, otherwise they will not work correctly. How to use the sync lock.

Synchronized keyword, which includes two usages: Synchronized method and synchronized block. Synchronized method:

1 Public synchronized void Countnum (int n);

All synchronized methods of a particular object share the same lock, which ensures that at most one time for each class instance, all of the member functions declared as synchronized are in the executable state (since at most one can obtain the lock of the class instance), This effectively avoids the access violation of class member variables (as long as all possible methods of accessing class member variables are declared as synchronized).

Also, static methods can be declared as synchronized to control their access to static member variables of the class.

1 public static synchronized void Countnum (int n);

The flaw of the Synchronized method: If a large method is declared as synchronized, it will greatly affect the efficiency.

Typically, if you declare the method run () of a thread class as synchronized, it will never succeed because it has been running throughout its lifetime, causing it to invoke any synchronized method in this class. Of course, we can do this by putting the code that accesses the class member variable into a specialized method, declaring it as synchronized, and tuning it in the main method to solve the problem, but Java provides us with a better solution, which is the synchronized block.

Synchronized Block:

1 2 3 Synchronized (Syncobject.class) {//Allow access control code}

It can also be written in the following format, this, which refers to the current class

1 2 3 Synchronized (this) {//Allow access control code}

A synchronized block is a block of code in which the code must obtain the lock of the object SyncObject (as described previously, can be a class instance or Class), and the specific mechanism is described in the previous instance. Because you can target arbitrary blocks of code, and can arbitrarily specify locked objects, so flexibility is high.

When using the synchronized block, be sure to follow the Brian synchronization rules and synchronize each method that accesses the critical shared resource.


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.