Results 1 to 2 of 2

Thread: Problem with compareAndSet in redis

  1. #1
    Join Date
    Apr 2012
    Posts
    9

    Default 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. #2
    Join Date
    Apr 2012
    Posts
    9

    Default

    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 at 05:01 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •