3 implementations of Java High concurrency lock

Source: Internet
Author: User

Beginner Tips-Optimistic lock

Optimistic locking is suitable for scenarios where reading does not conflict and writing conflicts. The frequency of reading is much larger than writing.

In the following code, for example, the implementation of pessimistic locks:

Java code

    1. public object get (object key) {

    2. synchronized (map) {

    3. if (map.get (key) = = null) {

    4. //Set some values

    5. }

    6. return Map.get (key);

    7. }

    8. }

Implementation of optimistic locking:

Java code

  1. public object get (object key) {

  2. Object val = null;

  3. if (val = map.get (key) = = null) {

  4. //When map value is NULL then lock judgment

  5. synchronized (map) {

  6. if (val = map.get (key) = = null) {

  7. //Set some value to map ...

  8. }

  9. }

  10. }

  11. return Map.get (key);

  12. }

Intermediate Tips-String.intern ()

Optimistic locking is not a good solution to a large number of write conflicts, but if many scenarios, the lock is actually for a user or an order. For example, a user must first create a session in order to perform subsequent operations. However, due to network reasons, the request to create a user session and subsequent requests are almost at the same time, while a parallel thread may handle subsequent requests first. In general, you need to lock the user sessionmap, such as the above optimistic lock. In this scenario, the lock can be limited to the user itself, that is, from the original

Lock.lock ();

int Num=storage.get (key);

Storage.set (key,num+1);

Lock.unlock ();

Change to:

Lock.lock (key);

int Num=storage.get (key);

Storage.set (key,num+1);

Lock.unlock (key);

This comparison is similar to the concept of database table locks and row locks, and apparently the concurrency of row locks is much higher than table locks.

Using String.inter () is a concrete implementation of this idea. Class string maintains a string pool. When the Intern method is called, if the pool already contains a string equal to this string object (which is determined by the Equals (object) method), the string in the pool is returned. It can be seen that when the String is the same, String.intern () always returns the same object, thereby enabling the same user to be locked. Because the granularity of the lock is limited to the specific user, the system obtains the maximum concurrency.

Java code

    1. Public void DoSomething (String uid) {

    2. synchronized (Uid.intern ()) {

    3. // ...  

    4. }

    5. }

Copyonwritemap?

Now that the "concept of row locks in a database is similar", we have to mention that the Copyonwrite class in Mvcc,java implements the MVCC. Copy on write is such a mechanism. When we read the shared data, we read it directly and do not need synchronization. When we modify the data, we copy the current data copy, then modify it on the copy, and then replace the original data with the modified copy. This method is called copy on Write.

However,, the JDK does not provide copyonwritemap, why? Here is a good answer, that is already has the concurrenthashmap, why still need Copyonwritemap?

Fredrik Bromee wrote

I Guess this depends the your use case, and why would you need a copyonwritemap when you already has a concurrenthashmap?

For a plain lookup table with many readers and only one or few updates it is a good fit.

Compared to a copy on write collection:

Read Concurrency:

Equal to a copy on write collection. Several readers can retrieve elements from the map concurrently in a lock-free fashion.

Write Concurrency:

Better concurrency than the copy on write collections This basically serialize updates (one update at a time). Using A concurrent hash map you have a good chance of doing several updates concurrently. If your hash keys is evenly distributed.

If you don't want to having the effect of a copy on write map, you can always initialize a concurrenthashmap with a concurrency Level of 1.

Advanced Tips-Class Concurrenthashmap

The flaw of String.inter () is that the class string maintains a string pool that is placed in the JVM Perm area, and if the number of users is particularly large, a string that is placed in the strings pool is not controllable, potentially causing an oom error or an excessive full GC. How to control the number of locks, while reducing the size of the lock? Use Java Concurrenthashmap directly? Or do you want to join your own finer control? So you can learn from the Concurrenthashmap way, will need to lock the object into multiple buckets, each bucket plus a lock, pseudo-code as follows:

Java code

    1. Map locks = new map ();

    2. List Lockkeys = new list ();

    3. for (int number: 1- 10000) {

    4. Object Lockkey = new Object ();

    5. Lockkeys.add (Lockkey);

    6. Locks.put (Lockkey, new Object ());

    7. }

    8. Public void DoSomething (String uid) {

    9. Object Lockkey = Lockkeys.get (Uid.hash ()% lockkeys.size ());

    10. Object lock = Locks.get (Lockkey);

    11. synchronized (lock) {

    12. //Do something

    13. }

    14. }

    15. For more free tutorials Please join Dubbo Technical Exchange: 548209960
      Java high concurrency High availability architecture: 632103578

3 implementations of Java High concurrency 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.