Reduce the range of synchronized

The code in the synchronized code block should be as little as possible to reduce the execution time of the code in the synchronized code block and reduce the lock competition.

synchronized(Demo1.class) {
    System.out.println("qwer");
}
Copy the code
  1. Synchronized has a shorter execution time, with more threads executing and fewer waiting threads per unit of time.
  2. Synchronized has a short execution time and can be done with lightweight or spin locks to avoid upgrading to heavyweight locks.

Reduces the granularity of synchronized locks

Splitting a lock into multiple locks improves concurrency

Hashtable

Hashtable hs = new Hashtable();
hs.put("a"."b");
hs.put("c"."d");
Copy the code

Synchronized “put”, “get”, and “remove” are synchronized methods.

ConcurrentHashMap

  1. The Get method of ConcurrentHashMap is unlocked.
  2. In the put method, cas and synchronized are used to add nodes, where synchronized uses the first element in the bucket instead of the same lock. When adding elements if none of the barrel inside an element, use the cas to add the first element, if there is vessel elements need to be in the future, will use the inside of the barrel of the first node as its object, which means that only locked inside a bucket list, will not affect the other threads to other bucket to add and delete operation.

Do not use the class name. Class as the lock to reduce the granularity of the lock and improve the concurrency efficiency

Reading and writing separation

Read without locking, write and delete with locking

ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteSet