Redis: Multithreading modifies the same key using watch+ transactions (mutil) for optimistic locking

Source: Internet
Author: User

This article is applied through the Watch (monitoring) +mutil (transaction) implementation to the relevant scenarios such as distributed high concurrency processing. The bottom of the Redis-cli.exe to test multiple thread modifications, encountered problems and solve the problem.

High concurrency to modify the same key encountered problems:

1) Define a hash type of Key,key: Lock_test, the value of element locker is initialized to 0.

2) Increase the value of the locker element for high concurrency: Define 64 multi-threading, and concurrently modify the value of the lock_test element Locker.

 Packagecom.dx.es;ImportJava.util.concurrent.CountDownLatch;ImportRedis.clients.jedis.Jedis;ImportRedis.clients.jedis.JedisPool; Public classTest_unlock { Public Static voidMain (string[] args) {FinalJedispool pool =Redisutil.getpool (); //get Jedis ObjectJedis Jedis =Pool.getresource (); Jedis.hset ("Lock_test", "Locker", "0"); String Val= Jedis.hget ("Lock_test", "Locker"); System.out.println ("The initial value of the Lock_test.locker is:" +val);        Jedis.close (); intThreahsize = 64; FinalCountdownlatch Threadscountdownlatch =NewCountdownlatch (threahsize); Runnable Handler=NewRunnable () { Public voidrun () {Jedis Jedis=Pool.getresource (); Integer integer= Integer.valueof (Jedis.hget ("Lock_test", "Locker")); Jedis.hset ("Lock_test", "Locker", string.valueof (integer + 1));                Jedis.close ();            Threadscountdownlatch.countdown ();        }        };  for(inti = 0; i < threahsize; i++) {            NewThread (handler). Start (); }        //wait for all parallel child thread tasks to complete.         Try{threadscountdownlatch.await (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Complete"); Val= Jedis.hget ("Lock_test", "Locker");    System.out.println (Val); }}

At this point, the following issues occur:

    1. A thread gets the value of key 0, and the b thread gets the value of Jkey 0, then a takes the key value to the 1,B thread and increments the key value to 1. Two threads have performed a key value modification: 0 to 1.
    2. In 1) The final key is modified to 1, but the C thread gets the value of key is 0 (because the C thread reads the key value, a, B thread has not triggered the modification, so the C thread reads a value of 0), the D thread reads a value of 1 (because the D thread reads the key value, a, b thread has triggered the modification A value of 1 is taken by the D thread at a time.
    3. Assuming that the D thread first triggers the increment, the D thread has modified the value by 2 before the C thread has triggered the commit, but C does not know at this time what has happened before it gets to the value and modifies the value 1 directly.

At this point, the print result is:

The initial value of the Lock_test.locker is: 0 Complete#备注: It could be another value, perhaps the correct value of 64 is less likely. 
Solve the above problem by watching (monitoring) +mutil (transaction): The transaction operation under Redis-cli.exe:
# The transaction was successfully executed by Redis127.0.0.1:6379>Multiokredis127.0.0.1:6379>INCR User_idqueuedredis127.0.0.1:6379>INCR User_idqueuedredis127.0.0.1:6379>INCR User_idqueuedredis127.0.0.1:6379>Pingqueuedredis127.0.0.1:6379>EXEC1) (integer)12) (integer)23) (integer)34) PONG
The watch+mutil operation is used in the case of concurrency:

The return value of all commands within a transaction block, sorted by the order in which they were executed. When the operation is interrupted, a null value of nil is returned.

A thread:

# Monitor key, and the transaction successfully executes Redis127.0.0.1:6379>WATCH Lock Lock_timesokredis127.0.0.1:6379>Multiokredis127.0.0.1:6379> SET Lock"Huangz"Queuedredis127.0.0.1:6379>INCR Lock_timesqueuedredis127.0.0.1:6379>EXEC1) OK2) (integer)1

B Thread:

# Monitor key, and the transaction is interrupted by Redis127.0.0.1:6379>WATCH Lock Lock_timesokredis127.0.0.1:6379>Multiokredis127.0.0.1:6379> SET Lock"Joe"# Just then, another client modified the value of Lock_times Queuedredis127.0.0.1:6379>INCR Lock_timesqueuedredis127.0.0.1:6379>EXEC # Because Lock_times was modified, Joe's transaction execution failed (nil)

The above shows the watch+mutil operation under a, B thread concurrency.

Need to master Redis transaction commands:

The watch command is used to monitor one (or more) key, and the transaction is interrupted if the (or these) key is modified by another command before the transaction executes. Available version: >= 2.2.0

tr>
       
       
  & nbsp;    
       
       
       
Serial Number Command and Description
1 DISCARD
Cancels the transaction, discarding all commands within the transaction block.
2 Exec
Executes the commands within all the transaction blocks.
3 MULTI
Marks the beginning of a transaction block.
4 Unwatch
Cancels the watch command's monitoring of all keys.
5 WATCH key [Key ...]
Monitor one (or more) key, and if this (or these) key is changed by another command before the transaction executes, the transaction will be interrupted.

Redis: Multithreading modifies the same key using watch+ transactions (mutil) for optimistic locking

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.