Java interview 03| concurrency and Locks

Source: Internet
Author: User
Tags cas mutex semaphore

1. The difference between synchronized and lock

There are some drawbacks to synchronizing blocks that are implemented using the SYNCHRONIZED keyword:

(1) There is only one type of lock

(2) thread gets locked or blocked

(3) lock is implemented in the Java language level based on the CAS spin mode to achieve the lock, under the concurrency conditions, its performance is relatively better than synchronized.

In order to solve the various problems, a more complex lock-thread locking was proposed later. The thread lock can be improved in several ways:

(1) Adding different types of locks, such as read locks and write locks (the primary implementation class is the Reentrantreadwritelock Class)

(2) There is no limit to the blocking of the lock, that is, it can be locked in one method and unlocked in another method.

Because Semaphore does not associate a license with a particular thread, the license obtained in one thread can be freed from another thread.

(3) If a thread does not get a lock, such as a lock held by another thread, it allows the thread to go back or continue, or do something else. such as using Trylock () and Trylock (Long,timeunit). When you find that an attempt to lock cannot be added, you can first release the lock that has been successfully added to the other objects, and then try again later to avoid deadlocks to some extent.

(4) Allow the thread to attempt to lock and discard after the wait time has passed.

The Reentrantlock implements the lock interface and provides the same mutex and memory visibility as the synchronized. When getting/exiting Reentrantlock, there is the same memory semantics as the Enter/exit synchronization code block. The locking semantics are also available for re-entry.

Reentrantlock has added some advanced features compared to synchronized, with 3 main items:

(1) waiting to be interrupted

(2) can achieve a fair lock (synchronized implementation of the non-fair lock)

(3) A lock can bind multiple conditions (one reentrantlock can bind multiple condition objects at the same time

Reentrantlock gets locked with three ways:
A) lock (), if the lock is acquired immediately and returns if another thread holds the lock, the current thread is dormant until the lock is acquired

b) Trylock (), if acquired the lock immediately returns true if another line is impersonating holds the lock, returns false immediately

c) Trylock (long timeout,timeunit unit) If the lock is acquired immediately returns true if another line is impersonating holds the lock, waits for the parameter given the time, in the process of waiting, if the lock is acquired, returns true if the wait timeout, Returns false

d) lockinterruptibly: If acquired lock is returned immediately, if no lock is acquired, the current thread is dormant until either locked, or when the thread is interrupted by other threads

2. Implementation of lock mechanism

The implementation of lock has a AQS mechanism inside it. AQS (Abstractqueuedsynchronizer) is an abstract class that manages "locks" in Java, and many of the public methods of locks are implemented in this class. Aqs is the public parent class for exclusive locks (such as reentrantlock) and shared locks (such as semaphore).

The queue is the thread queue for "Waiting for locks" in Aqs. In multi-threading, in order to protect competing resources from being manipulated by multiple threads at the same time, we often need to secure these resources through locks. In an exclusive lock, a competing resource can only be accessed by one thread lock at a time, while the other thread waits. Queues are queues of threads that manage these "wait locks".

The queue is a non-blocking FIFO queue. That is, when inserting or removing a node inside, it is not blocked in concurrency, but the atomicity of node insertion and removal is ensured through spin locks and CAS .

For example, such as an exclusive lock reentrantlock. Reentrantlock is divided into "fair lock" and "non-fair lock". The difference between them is fair in the mechanism of acquiring locks. Reentrantlock is a FIFO waiting queue to manage all threads that acquire the lock.

(1) Under the mechanism of "fair lock", threads queue to acquire the lock in sequence;

(2) "unfair lock" when the lock is available, regardless of whether the lock is acquired at the beginning of the queue.

Take the implementation of the non-fair lock as an example, as follows:

The implementation process for releasing the lock is as follows:

Reference article:

(1) http://tech.meituan.com/distributed-system-mutually-exclusive-idempotence-cerberus-gtis.html

3, the source code analysis Aqs in several synchronization tool class use

See this article in more detail:

(1) http://ifeve.com/abstractqueuedsynchronizer-use/#more-18899

(2) Countdowlatch principle of implementation: http://blog.csdn.net/yanyan19880509/article/details/52349056

until the count is decremented to 0.
Tool class Tool class function Method of locking Tool class Tool Class Release Lock method Sync Overlay/Non-covered method The role of State and the type of lock Lock Maintenance
Semaphore Control the number of operations that concurrently access a specific resource Acquire: Each request for a license will cause the counter to decrease by 1, and once the 0 is reached, the new license request thread will be suspended Release: Add a license per call to release a blocked fetch

Covered:

Tryacquireshared tryreleaseshared

Indicates the number of licenses initialized

Shared locks

Each request acquire () a license will cause the counter to be reduced by 1, as well as releasing a license release () each time it will cause the counter to increase by 1, and once the 0 is reached, the new license request thread will be suspended.
put a set of threads out of the box and let go of a certain state. A synchronization mechanism to ensure that one or more threads wait for other threads to complete. await: block the calling thread when the counter is not 0, return immediately for 0 times countdown: Decrement count tryacquireshared tryreleaseshared

Maintain a counter

Shared lock

Initialize a count, Each time the Countdown method count is decremented, the thread calling await will block
reentrantlock standard mutex, i.e. only one thread can hold a lock at a time lock: Returns immediately if no thread is used, and sets state to 1 if the current thread already occupies a lock, state plus 1, if the other thread occupies the lock, the current thread is unavailable, waits for Trylock: If the lock is available, the lock is acquired. And immediately returns the value TRUE. If the lock is not available, this method returns the value immediately to false unlock: Attempts to release the lock, if the current thread occupies the lock, Count minus one, and if Count is 0, the lock is released. If the owning thread is not the current thread, throw an exception Overwrite:

Tryacquire

Tryrelease

 

Non-overwrite:

Nonfairtryacquire

State indicates the thread that acquired the lock

Number of times the lock was re-entered

Exclusive lock

When a lock is acquired, it is returned immediately if no thread is used, and the state is set to 1, if the current thread already occupies the lock, State plus 1, or if the other thread occupies the lock, the current thread is unavailable. When a lock is released, the primary role in the method is to reduce the state status bit to release, which means that the lock is released, if the updated state is 0, indicating that the current thread is releasing the lock, and if not 0, the current thread that holds the lock has a decrease in the number of re-entry
reentrantreadwritelock read-write lock. Allows multiple read threads to hold locks at the same time, but only one write thread can hold the lock. After the write thread acquires the write lock, the read lock can be acquired again, but the read lock cannot acquire the write lock readlock#lock: Gets the read lock Readlock#trylock: The attempt to obtain a read lock when no other thread currently holds a write lock Writelock#lock: Gets the Write lock Writelock#trylock: An exhalation write lock is attempted when no other thread is currently holding a write lock. readlock#unlock: Release read lock Writelock#unlock: Release write lock

Overwrite:

acquireshared releaseshared

Tryacquire

Tryrelease

Non-overwrite:

Tryreadlock trywritelock

High 16-bit indicates the number of shared locks,

Low 16 bits for exclusive lock re-entry

Read lock: Share

Write Lock: Exclusive

Futuretask Encapsulates an execution task to be executed by another thread, which can be canceled after execution, and can view the execution result and block if the execution result is not completed. V get ()

Run ()

Set (V)

Cancel (Boolean)

Covered:

Tryacquireshared tryreleaseshared

Non-covered:

Innerget Innerrun () Innerset inneriscancelled

State bit to store execution state running, run, CANCELLED

Shared locks

The thread that gets the result of the execution (which can have multiple) is blocked until the thread executing the task finishes, or the execution task is canceled.

Java interview 03| concurrency and Locks

Related Article

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.