Use the shared cache redis to implement distributed mutex lock and cache redis for mutex
The newly developed system needs to control one and only one GC thread that recycles the cache at a time. If multiple threads run simultaneously, the system will crash. If there is only one JVM process, you can simply use the synchronized keyword. However, my system needs to be deployed on multiple servers, with each server deployed on multiple instances. Synchronized is only useful in a single process.
Consider using the shared data source redis.
Redis provides a method called SETNX key value. Set the key value to value if and only if the key does not exist. If the given key already exists, SETNX does not take any action. Set successfully. 1 is returned. Setting failed. 0 is returned.
The key is a lock. If 1 is returned, the mutex lock is obtained successfully and then enters the critical section. 0 is returned, indicating that the acquisition failed and the system cannot enter the critical section.
Sample Code:
Try {mutex = KeyHelper. data. risk. getGcThreadMutexKey (); if (dataCommonCacheService. setnx (mutex, "OK") = 1L) {// try to lock garbageCollector. garbageRecycle (); // critical section} catch (Exception e) {LOG. error (e. getMessage (), e);} finally {dataCommonCacheService. del (mutex); // release the lock}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.