The newly developed system needs to control the GC thread that recycles the cache at every moment and only one is running, which can cause the system to crash if there are multiple threads running concurrently. If only one JVM process is so good, simply use the Synchronized keyword. But my system is going to be deployed on multiple servers, on each server, on more than one instance. And synchronized is only useful in a single process.
Consider using the shared data source Redis implementation feature.
Redis provides a way to setnx key value. Set the value of key to value when and only if key does not exist. If the given key already exists, then SETNX does not do any action. Set success, return 1. Setting failed, returns 0.
Then this key is a lock, if return 1, the acquisition of the mutex is successful, then you can enter the critical section. Returns 0, indicating that the acquisition failed to enter the critical section.
Example 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 Lock}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Implementing distributed mutexes with shared cache Redis