Use the shared cache redis to implement distributed mutex lock and cache redis for mutex

Source: Internet
Author: User

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.

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.