Home > other >  Does the command WATCH in Redis behave in the same way as volatile variable in Java?
Does the command WATCH in Redis behave in the same way as volatile variable in Java?

Time:01-25

I'm a bit hesitating in terms of how Redis transaction concept works.

As fas as I know transaction is list of command between multi and exec which is not executed immediately, but this deferred until exec will be called.

Let's assume that I put some value to Redis in atomic way:

MULTI
  get current value and increment
EXEC

Exectly at this momemt new thread comes and try to read value which was stored as shown above. Does it mean that this value will be unavailable until transaction will be finished and this thread will perform his logic in wrong way since this value has not been read ?

And in order to give possibility for thread to read this value meanwhile transaction is running I need to use WATCH which does definitely the same as volatile variable - stores access to value which is kind of blocked by transactions ?

CodePudding user response:

Please check the Redis Transactions documentation - https://redis.io/topics/transactions.

First, you need to recall that Redis is single threaded. When you send a command after calling MULTI Redis doesn't execute the command and just QUEUED it. Only, when EXEC is call then the main thread (the only execution thread) is running all the QUEUED commands in the transaction. So, no other client can read part of the traction.

As for WATCH, it's not used as volatile but only as an indicator for Redis that if this key was changed between the call to WATCH and the call to EXEC the transaction shouldn't fail not committed.

Using WATCH one can assure that any reads done between the WATCH and MULTI are still valid by the time EXEC is called.

  •  Tags:  
  • Related