What is the advantage of the new Lock interface over the synchronized block in Java?

What is the advantage of the new Lock interface over the synchronized block in Java? You need to implement a high-performance cache that allows multiple readers, except one writer, to maintain integrity, how do you implement it?

+4
source share
2 answers

Blocking Benefits

  • You can make them honest.
  • it is possible to make a thread responsive to interrupt while waiting for a Lock object.
  • it is possible to try to get a lock, but immediately or after a timeout if the lock cannot be obtained
  • it is possible to acquire and release locks in different areas and in different orders

Note that this is explained in javadoc Lock and its subclasses.

High performance cache can be implemented using ConcurrentMap.

+10
source

You need to know when to use Lock and when to use synchronized blocks / methods.

  • Use synchronized blocks if you are building simple applications. This avoids race conditions. But, avoiding race conditions, you can cause deadlocks.

  • Use Locks if you are creating serious applications. It also avoids race conditions, but you can also avoid deadlocks.

-4
source

Source: https://habr.com/ru/post/1379847/


All Articles