Common locks, that is, in a single-threaded environment, when multiple threads need to access the same variable or code fragment, the variable or code fragment being accessed is called the critical region. We need to control the thread execution sequence one by one, otherwise concurrency problems will occur.

Setting a flag that each thread can see is his control mode. When each thread wants to access a critical region, it first looks at flags. If the flags are not occupied, no thread is currently accessing the critical region. If the flag is occupied, a thread is currently accessing the critical region, and the current thread needs to wait. This symbol is the lock.

In a distributed environment, where there are multiple machines, each of which starts the JVM execution program, if threads on different machines want to access a critical region, the way normal locks use variables in heap memory is definitely not appropriate.

According to the nature and principle of the lock, we need to find another flag visible to the threads of multiple machines, to it as a lock, it is ok. Such a lock is called a distributed lock.

Distributed locks should have the following conditions:

1. In distributed system environment, a method can only be executed by one thread of a machine at a time;

2. Highly available lock acquisition and lock release;

3, high-performance lock acquisition and lock release;

4, with reentrant characteristics;

5, with lock failure mechanism to prevent deadlock;

6, with non-blocking lock feature, that is, did not get the lock will directly return to obtain the lock failure.

We are in the development of applications, if the need for a shared variable multithreaded synchronization access, we can use the Java multithreaded 18 like arts for processing, and can be perfect operation, no bug!

Note that this is a stand-alone application, meaning that all requests are allocated to the current server’s JVM and mapped to the operating system’s thread for processing! The shared variable is just a chunk of memory inside the JVM!

Free Java interview questions