Announcement Announcement Module
Collapse
No announcement yet.
Problem with compareAndSet in redis Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Problem with compareAndSet in redis

    Hi,

    I think there is an error with the method compareAndSet in redis Data 2.1.0.
    As far as I know this method is atomic, so it cannot be set the value more than once but if you execute the code below it does.
    Code:
    	public void testCompareSet() {
    		for (int i = 0; i < 500; i++) {
    		    Inner r = new Inner();
    		    new Thread(r).start();
    		}
    	}
    	 private class Inner implements Runnable {
    
    		@Override
    		public void run() {
    			RedisAtomicInteger atomicInteger = 
    					new RedisAtomicInteger("key", redisConnectionFactory);
    			System.out.println(atomicInteger.compareAndSet(0, 1));
    		}
    	 }
    The output of this is:

    false
    false
    false
    false
    true
    false
    false
    false
    false
    false
    false
    false
    false
    true
    false
    false
    false
    false
    true
    false
    false
    false
    true
    false
    false
    .......

    Am I missing anything?

    Thanks

  • #2
    I'm looking into the code:
    Code:
    	public boolean compareAndSet(final int expect, final int update) {
    		return generalOps.execute(new SessionCallback<Boolean>() {
    
    			@SuppressWarnings("unchecked")
    			
    			public Boolean execute(RedisOperations operations) {
    				for (;;) {
    					operations.watch(Collections.singleton(key));
    					if (expect == get()) {
    						generalOps.multi();
    						set(update);
    						if (operations.exec() != null) {
    							return true;
    						}
    					}
    					{
    						return false;
    					}
    				}
    			}
    		});
    	}
    And I'm wondering if the call to MULTI shouldn't be done before the get, so it makes sure that only one reads the old value.
    Last edited by flopezluis; Oct 15th, 2012, 06:01 AM.

    Comment

    Working...
    X