Implementing distributed mutexes with shared cache Redis

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.