Java implements distributed locks

Distributed lock?

Answer: Control the synchronous access of distributed systems to shared resources.

 Introduction to some implementation methods

( 1 ) Implementation based on database

        When a method or resource is to be locked, a record is added to the table, and the record is deleted when the lock is released.

   There are problems: 1. The lock is non-reentrant, and the same thread cannot acquire the lock again without releasing the lock because the data in the database already exists. 

                           2. The lock is non-blocking, because the data insert fails to report an error directly, and the thread that does not obtain the lock will not enter the queue. 

                           3. Once the unlocking fails, the lock record will always exist in the database, and other threads cannot obtain the lock.

(2) Implementation based on cache

     Use redis . SETNX+GETSET command.

     Lock key foo : client tries SETNX foo.lock <current time>

     If it returns 1 , the lock is successful, and 0 is returned , indicating that other clients hold the lock, call GET to get the timestamp T1 of foo.lock , if the lock times out, send the GETSET command to get the old timestamp T2 , if T1=T2 , the lock is successful. If T1!=T2 , it means that other clients get the lock first.

(3)Zookeeper



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325642516&siteId=291194637