Large head makes a variety of locks, from here makes you think more clearly

personal blog

personal blog

This time we look at lock

Speaking of the lock we often think of life in the lock, in our daily life we ​​often come into contact with the lock. For example, our phone lock, computer lock, another example of our lives locks, these are the locks.

Lock What role do?

Having said that locks in the end still do not know what is the use? It is necessary to ponder why we have to use the lock, we use the phone lock is to protect our privacy, use locks to protect our property safe and accurate for us is to use the safety lock.
So in our lives can be locked to protect their privacy and property safety, lock it in Java What use is it?

Java in the lock

Java in the lock is also accurate in order to ensure safety, but the difference is in Java locks are needed in order to ensure concurrency. So accurate is locked in Java concurrency is to ensure safety, but also to solve the consistency of memory, atomicity, ordering three kinds of problems. Offers a wide variety of locks in Java, each lock has its own characteristics and scope of application. So we have to be familiar with the difference between the lock and the principle of the right to use.

Optimistic and pessimistic locking

Pessimistic locking

Optimistic and pessimistic locking, then just before I started writing when he wrote a related article, where you re-introduce it.
Pessimistic locks As the name implies it is pessimistic, it felt every time access to the data are likely to be other people (threads) to modify, so it will be a resource lock when accessing resources in this way to ensure that resource in time of the visit It will not be modified by other threads. This is the case, then other threads want access to resources can only be blocked until the current thread releases the lock after the acquisition. In the implementation in Java are pessimistic locking synchronized关键字and Lockimplementation classes are pessimistic locking. We look pessimistic locking in the end is how to perform.

A thread after thread B seize the resources caught in the obstruction, and then wait for the thread A to release resources.

When the thread A thread B releases End resources went to get a lock to start operating resources ˛ pessimistic locking ensures that only one thread at the same time resources to operate.

Optimistic locking

In contrast with the pessimistic locking, optimistic locking does not feel when someone will access data modification (so it is optimistic), it does not lock when accessing resources, but at the time it filed to go back to judge whether someone changes current data in the database, we can use the versionversion number to be realized. In Java, we are using the CSA to achieve. We look optimistic locking execution

CASE

CAS (Compare And Swap) algorithm is an algorithm for lock-free, non-blocking atomic operations provided by Java. Under the multi-thread synchronization without the use of locks. And in the contract (the java.util.concurrent) CAS atoms class are used to implement optimistic locking. CAS hardware to ensure that the updated comparison atoms, provides a series of methods in the JDK compareAndSwap * Unsafe, Unsafe this class will not go into here.
CAS operating procedure is to in-memory data to be modified with the expected value, if the two values are equal to the value of the new modified value, or not doing that is operating CAS requires three operating values:

  • The expected value of A
  • Memory V
  • Will be modified B

    Simple, CAS is an infinite loop, determine the expected value and the value in the loop memory are equal, if they are equal, then the implementation of modifications, if not equal, then if it continues to cycle until after the implementation of a successful exit.

    CAS issues

    CAS Although very fast hardware, but it has some problems such as the ABA problem, for example, now has a shared memory variable X is A, this time the emergence of a variable that you want to change the value of the variable X, will first get this time acquired value X is a, then the CAS operation variable X is modified to B. Such seems to be no problem, and that if acquired after the thread variable X 1, appeared before the implementation of CAS value of a thread 2 X modified to B and then execute CAS operations and modified into the A, although the final results of the implementation of shared variables a value of a but this is not a thread a 1 obtain.
    This is the classic problem of ABA. ABA problem is generated because the state variable value has cycloconverter, A may to B, B to be A, if A to B, B to C such a problem does not occur.

    Solution: After JDK1.5 joined the AtomicStampedReference method for adding a time stamp for each variable to avoid the ABA problem.
    At the same time there is a large loop overhead CAS problem, because it will have been successful until the expected cycle equivalent modifications and memory. At the same time there can only guarantee atomic issue a shared variable but added AtomicReference class after JDK1.5 to ensure atomicity references between objects.

    Use pessimistic locking and optimistic locking

You may be used to implement the synchronized keyword pessimistic locking, and optimistic locking method may be used provided the atomic packet type.

Fair and unfair lock lock

He says the optimistic and pessimistic locking lock, and now look fair and unfair lock lock. In the lock is fair and unfair drops, fair locks its name the emphasis is on a level playing field, so multiple threads simultaneously apply for application lock, then thread into a queue, the first in the queue to enter the queue thread resources to acquire the lock, the emphasis is on first come first served. For example, we would Dafan in the school cafeteria when that time I remember my classmates to go straight to the cafeteria line up quickly so the rice can be marked as soon as possible, and in the process queue and no one can not eat rice, this time canteen aunt It is fair for everyone queuing words can eat rice, thread too. Unfair lock can be understood, that my students to the cafeteria line up Dafan up but some people jump the queue, canteen aunt is not fair to jump the queue Dafan people do not give him a straight, you say gas is not gas is not unfair, Key non-equity plan is not necessarily a lock first-served basis . But fair lock is flawed, when a thread gets resources from other threads in the queue will only be blocked, so fair lock CPU is much less efficient than non-fair locks. Because the CPU overhead blocked thread wake larger than non-fair locks. A look at an example:

In Java ReentrantLock lock provides fair and unfair achieve lock. ReentrantLock look at how to achieve fair and unfair lock lock

Fair and unfair use lock lock

ReentrantLock default lock is unfair, let's look at an example of fair locks:

a look at the output:

we can see the output is in the order of fair locks come, first-served basis.
In a look at the non-lock fair example:

output:

we can see the result if a non-fair locks if the final output is absolutely no order, not necessarily first come first served basis.
So when using a fair lock thread after thread 1 get 2 to lock in the lock, then the request will hang waiting thread 1 releases the lock, then thread 2 in order to obtain a lock. If we want to have a thread requesting the lock, then 3, non-fair locks at this time if used, the thread 2 and 3 have two threads will get to a lock, lock fair case can only suspend a thread 3, after waiting thread 2 acquires the lock release resources acquired.

When using unfair fair locks and lock

Fair use under the scenario requires a fair lock resources, if no special fair to fair, then try to use non-lock, the lock will bring fair because the cost of performance.

Exclusive lock and a shared lock

See exclusive and shared think of what, for the exclusive lock that only one thread can occupy the lock resources, while others can only wait for the current thread to acquire the lock resource thread releases the lock in order to acquire the lock again, just above ReentrantLock is the exclusive lock, it would appear that an exclusive lock is not pessimistic lock on it? Because after the pessimistic locking seize the resources can only wait for the release of another thread can acquire the lock resource again. In fact accurate to say that an exclusive lock is also pessimistic locking.
Talking about shared lock, shared lock is actually optimistic locking lock it relaxed the policy to allow multiple threads simultaneously acquire a lock. And contracting in the ReadWriteLock is a typical shared lock. It allows a resource that can be read multiple access, or access was a write operation, but not both at the same time.

Spinlocks

What is the spin lock spin lock in fact, when a thread gets the lock, the lock has been acquired to other people so this thread does not immediately hang, but without giving up the right to use the CPU will try to get again lock resource, the default number is 10, you can use -XX: PreBlockSpinsh set number of times. If the spin-lock acquire a lock for too long will cause the thread behind the CPU resource depletion released. And a spin lock is not fair.

advantage

Spin lock state does not make the thread switch occurs has been in user mode, i.e., the thread has been active; does not cause the thread to enter the blocked state, reducing unnecessary context switching, fast execution.

Life there are all sorts of unexpected conditions, Java also has a variety of unexpected abnormal, the next time we talk about abnormal Java, welcome to forward concerns

Guess you like

Origin www.cnblogs.com/Scramblecode/p/11570608.html