Java multithreaded Programming--Lock optimization

Source: Internet
Author: User

When programming in a concurrent environment, it is necessary to use the lock mechanism to synchronize the operation between multiple threads to ensure mutually exclusive access to shared resources. Locking can cause performance damage, which seems to be a well-known thing. However, the lock itself does not bring much performance consumption, the performance is mainly the process of acquiring locks on the thread. If there is only one thread competing for the lock, there is no multi-threaded competition, then the JVM will be optimized, then the performance consumption of locking can be ignored. Therefore, the specification lock operation, optimizes the use method of the lock, avoids the unnecessary thread competition, may not only improve the program performance, but also can avoid the non-standard locking may cause the thread deadlock problem, enhances the program robustness. The following is a description of several lock optimization ideas.

First, try not to lock the method

When a lock is added to an ordinary member function, the thread obtains the object lock of the object on which the method resides. The entire object will be locked at this time. This also means that if the object provides multiple synchronization methods for different businesses, then because the entire object is locked, and a business business is processing, other unrelated business threads must wait. The following example shows the situation:

The LockMethod class contains two synchronous methods, which are called in two business processes, respectively:

Copy code public class LockMethod {public synchronized void Busia () {for (int i = 0; i < 10000; i++) {System.out.println ( Thread.CurrentThread (). GetName () + "deal with bussiness A:" +i);} Public synchronized void Busib () {for (int i = 0; i < 10000; i++) {System.out.println (Thread.CurrentThread (). GetName ( ) + "deal with bussiness B:" +i);}}

Bussa is a threading class that is used to handle a business, calling LockMethod's Busia () method: public class Bussa extends thread {LockMethod lockmethod; void Deal ( LockMethod lockmethod) {this.lockmethod = LockMethod;}

@Overridepublic void run() {    super.run();    lockMethod.busiA();}

}

BUSSB is a thread class that is used to handle the B business, calling LockMethod's Busib () method: public class Bussb extends thread {LockMethod lockmethod; void Deal ( LockMethod lockmethod) {this.lockmethod = LockMethod;}

@Overridepublic void run() {    super.run();    lockMethod.busiB();}

}

The Testlockmethod class, which uses thread Bussa and BUSSB for business processing: public class Testlockmethod extends thread {

public static void main(String[] args) {    LockMethod lockMethod = new LockMethod();    BUSSA bussa = new BUSSA();    BUSSB bussb = new BUSSB();    bussa.deal(lockMethod);    bussb.deal(lockMethod);    bussa.start();    bussb.start();}

}

Running the program, you can see that the process of Bussa execution, BUSSB is not able to enter the function Busib (), because the LockMethod object lock is obtained by thread Bussa.

Second, narrow the synchronization code block, lock only the data

Sometimes for programming convenience, some people will synchnoized a very large piece of code, if some operations in this code block are not related to shared resources, then you should put them outside the synchronization block, to avoid long holding locks, causing other threads have been waiting state. In particular, some cyclic operations, synchronous I/O operations. Not only in the range of lines of code to narrow the synchronization block, in the execution of logic, you should also reduce the synchronization block, such as additional conditions to determine, meet the conditions of the synchronization, rather than synchronization after the conditional judgment, to minimize unnecessary logic to enter the synchronization block.

Third, try not to include the lock in the lock

This happens frequently, after the thread has got a lock, the synchronous method of the synchronization methods block calls the synchronization method of the other object, the second lock is obtained, which may lead to a multiple lock request in the call stack, the multi-threaded case can be complex, difficult to analyze the abnormal situation, resulting in the occurrence of deadlocks. The following code shows the situation:

Synchronized (A) {

Synchronized (B) {

  }  
    • 1
    • 2

}

Or a synchronous method is called in the synchronization block:

Synchronized (A) {

B  b = objArrayList.get(0);b.method(); //这是一个同步方法

}

The solution is to jump out of the lock, do not include lock: {b b = null;

Synchronized (A) {b = objarraylist.get (0);} b.method (); }

Four, the lock is privatized, the internal management lock

The lock as a private object, the outside can not get this object, more secure. The object may be locked directly by another thread, at which point the thread holds an object lock on the object, such as the following: class A {public void method1 () {}}

Class B {public void method1 () {A A = new A (); synchronized (A) {///Direct lock a.method1 ();

    }}

}

In this way, object A's object lock is held externally, so that it is more dangerous to use the lock in many places outside, and it also puzzles the logic flow reading of the code. A better way is to manage the lock itself within the class itself, while the external synchronization scheme is required to provide synchronization by means of an interface: class A {private Object lock = new Object (); public void Method1 () {SYNCHR Onized (lock) {

    }}

}

Class B {public void method1 () {A A = new A (); A.method1 ();}}

With 1-5 working experience, in the face of the current popular technology do not know where to start, need to break through the technical bottleneck can add group. Stay in the company for a long time, have a very comfortable, but job-hopping interview wall. Need to study in a short period of time, job-hopping to get a high salary can add group. If there is no work experience, but the foundation is very solid, on the Java work mechanism, common design ideas, Common Java Development Framework Master skilled can add group. Java Architecture Group: 6,975,797,511 AC

Java multithreaded Programming--Lock optimization

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.