java-Concurrent-lock&&synchronized

Source: Internet
Author: User

Sychronized

Lock the code block and execute the code block.

Release Lock:

1. The thread that gets the lock finishes executing and releases the lock's possession

2. Execution exception occurs, the JVM lets the thread automatically release the lock

Disadvantages:

1. Exceptions will only be thrown, cannot be resolved, maintenance system is normal

Lock

public interface lock{

void lock ();//Gets the lock, the lock is fetched by another thread, waits

void Lockinterruptibly () throws interruptedexception;

Boolean trylock ();//success->true;fail->false

Boolean Trylock (long time,timeunit unit) throws Interruptedexception;

void unlock ();

Condition newcondition ();

}

<lock () >

Lock Lock=new Reentrantlock ();//reentrantlock implements lock with the same concurrency and memory semantics

There is a lock-related get counter, a thread that owns the lock gets the lock again, +1,e.g. Exits the second synchronized block, does not release the lock, exits the first synchronized block, releases the lock

try{

}finally{

Lock.unlock ();//In Finally, ensure that the lock must be released
}

Lock must be released in finally, otherwise throws an exception

<trylock () >

Boolean Captured=lock.trylock ();

try{

}finally{
if (captured)

Lock.unlock ();

Else

...//not acquired to lock

}

<trylock (Long time,timeunit) throws Interruptedexception;>

try{

Boolean captured=trylock (2,timeunit.seconds);

}catch (Interrupedexception e) {

throw new RuntimeException (e);

}

try{

}finally{
if (captured)

Lock.unlock ();

Else

....}

See the interesting ... The locking mechanism used to traverse node passing through the node in the linked list

Come here first.

java-Concurrent-lock&&synchronized

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.