Java Thread Safety Lock

Source: Internet
Author: User

Java.util.concurrent.locks

For thread safety we used the Synchronized keyword earlier, and for thread collaboration we used object.wait () and object.notify (). In JDK1.5 Java provides us with lock to achieve the same functionality as they do, and performance outperforms them, and in JDK1.6, the JDK is optimized for synchronized, and the performance gap is small.

First, why do you appear lock

Synchronized-Modified code block, when a thread acquires a corresponding lock and executes the block, the other threads can only wait until the thread that acquires the lock releases the lock and waits indefinitely if it is not released. The thread that acquires the lock releases the lock only in two cases:

1. The thread that acquires the lock executes the code block, and then the thread releases the possession of the lock.

2. The thread execution exception occurs when the JVM causes the thread to automatically release the lock.

Lock vs. Synchronized:

1, lock is not built into the Java language, synchronized is the Java language keyword, so it is built-in features. Lock is a class that enables simultaneous access through this class.

2, synchronized do not need to manually release the lock, when the synchronized method or synchronized code block execution, the system will automatically let the thread release the lock, and lock must be the user to manually release the lock, if there is no active release lock, It is possible to cause a deadlock phenomenon.

second, the class and interface commonly used in Java.util.concurrent.locks package.
 Public InterfaceLock {//used to obtain a lock. Waits if the lock has been fetched by another thread.     voidLock (); //When This method is used to acquire a lock, if the thread is waiting for the lock to be acquired, the thread can respond to the interrupt, that is, the wait state of the disconnected thread    voidLockinterruptibly ()throwsinterruptedexception; //it represents an attempt to acquire a lock, and returns True if it succeeds, or false if the fetch fails (that is, the lock has been fetched by another thread)    BooleanTrylock (); //similar to the Trylock () method, except that the method waits for a certain amount of time when the lock is not reached, and returns False if the lock is not held within the time period. Returns true if the lock was obtained at the beginning or if the lock was obtained during the wait period.     BooleanTrylock (LongTime, Timeunit unit)throwsinterruptedexception; //Release Lock    voidunlock (); Condition newcondition ();}

1. Lock and Unlock
Lock is used to acquire a lock, but it does not actively release the lock and needs to be used in conjunction with unlock (). It is generally necessary to use lock in the try{}catch{} block, and the release lock operation is placed in the finally block to ensure that the lock must be released to prevent the occurrence of deadlocks.

 Packagecom.jalja.base.threadTest;ImportJava.util.concurrent.locks.ReentrantLock; Public classLocktestImplementsrunnable{ Public StaticReentrantlock lock=NewReentrantlock ();  Public Static intC=0;  Public voidrun () { for(inti=0;i<1000;i++) {lock.lock ();//Get lock            Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Get Lock"); System.out.println (Thread.CurrentThread (). GetName ()+ "====>" +c); C++; } Catch(Exception e) {e.printstacktrace (); }finally{System.out.println (Thread.CurrentThread (). GetName ()+ "Release lock"); Lock.unlock ();//Release Lock            }        }    }     Public Static voidMain (string[] args) {Locktest LT=Newlocktest (); Thread Thread1=NewThread (LT); Thread thread2=NewThread (LT);        Thread1.start ();        Thread2.start (); Try{thread1.join ();        Thread2.join (); } Catch(interruptedexception e) {e.printstacktrace ();    } System.out.println (c); }}

Note: The same thread can obtain the same lock continuously, but must also release the same number of locks. Allow the following wording

Lock.lock ();//Get lockLock.lock ();            Lock.lock (); Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Get Lock"); System.out.println (Thread.CurrentThread (). GetName ()+ "====>" +c); C++; } Catch(Exception e) {e.printstacktrace (); }finally{System.out.println (Thread.CurrentThread (). GetName ()+ "Release lock"); Lock.unlock ();//Release LockLock.unlock ();//Release LockLock.unlock ();//Release Lock}

2. Get lock Wait Time trylock (long, timeunit unit)
If you ask a friend to play basketball, the appointment time to your friend has not appeared, you wait 1 hours or not, I think you will be disappointed to leave. This is also the case for threads, because usually we cannot tell why a thread cannot get a lock, but we can give the thread a time limit for acquiring the lock, and if the lock is not acquired by the time, then the acquisition lock is discarded.

 Packagecom.jalja.base.threadTest;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.locks.ReentrantLock; Public classTrylocktestImplementsrunnable{ Public StaticReentrantlock lock=NewReentrantlock (); Private Static intM=0;  Public voidrun () {Try {            if(Lock.trylock (1, timeunit.seconds)) {//set the wait time to get the lock 1 secondsSystem.out.println (Thread.CurrentThread (). GetName () + "Get Lock"); M++; //Thread.Sleep (+);//set sleep 2 seconds}Else{System.out.println (Thread.CurrentThread (). GetName ()+ "Not acquired lock"); }        } Catch(Exception e) {e.printstacktrace (); }finally{            if(Lock.isheldbycurrentthread ()) {lock.unlock (); }        }    }     Public Static voidMain (string[] args) {trylocktest thread1=Newtrylocktest (); Trylocktest thread2=Newtrylocktest (); Thread Th1=NewThread (THREAD1); Thread Th2=NewThread (THREAD2);        Th1.start ();        Th2.start (); Try {            //let the main thread wait for the Th1, Th2 thread to finish executing, and then continue executionTh1.join ();        Th2.join (); } Catch(interruptedexception e) {e.printstacktrace ();    } System.out.println (M); }}

Execution Result:

thread-0 Get lock Thread-1 Get lock 2

The code is to let the thread in the lock request, wait up to 1 seconds, if more than a second without obtaining a lock to return false, if the lock is obtained to return true, according to the results can be seen Thread-1 thread in 1 seconds to obtain a lock.

We turn on the note//thread.sleep (2000); you will find that Thread-1 or Thread-0 must have an unlocked lock, because the thread that occupies the lock is 2 seconds, and the waiting time for the lock is 1 seconds, so it discards the request lock operation in the instant after 1 seconds.

Java Thread Safety Lock

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.