### Question:
JedisUtil { public static final Tuple popKeyFromZset(String zsetName) { Pipeline pipeline = JedisFactory.getJedis().pipelined(); try { pipeline.watch(zsetName); Response<Set<Tuple>> results = pipeline.zrangeWithScores(zsetName, 0, 0); pipeline.multi(); pipeline.zremrangeByRank(zsetName, 0, 0); pipeline.exec(); pipeline.sync(); Set<Tuple> values = results.get(); if (values.size() > 0) { return values.iterator().next(); } } catch (Exception e) { try { pipeline.discard(); } catch (Exception e1) { } e.printStackTrace(); } return null; }  static final Tuple popKeyFromZset(String zsetName); static final void cleanRedis(); static final void deleteAllKeys(); static final void deleteAllKeys(Jedis jedis); static void main(String ... args);  }### Answer:
@Test public void testPopKeyFromZset() throws Exception { Pipeline pipeline = JedisFactory.getJedis().pipelined(); Random r = new Random(); int max = 10000; for ( int i=0; i<max; i++ ) { pipeline.zadd(zsetName, r.nextInt(), "value_"+i); } pipeline.sync(); final AtomicInteger counter = new AtomicInteger(0); Thread t1 = new Thread(new Runnable() { public void run() { try { Tuple pop = JedisUtil.popKeyFromZset(zsetName); while ( pop != null ) { pop = JedisUtil.popKeyFromZset(zsetName); counter.incrementAndGet(); } } catch (Exception e) { e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { public void run() { try { Tuple pop = JedisUtil.popKeyFromZset(zsetName); while ( pop != null ) { pop = JedisUtil.popKeyFromZset(zsetName); counter.incrementAndGet(); } } catch (Exception e) { e.printStackTrace(); } } }); t1.start(); t2.start(); t1.join(); t2.join(); Thread.sleep(1000); System.out.println(counter); assertEquals(max, counter.intValue()); }
@Test public void testPopKeyFromZsetUnique() throws Exception { for ( int t=0; t<100; t++ ) { Pipeline pipeline = JedisFactory.getJedis().pipelined(); Random r = new Random(); int max = 100; for ( int i=0; i<max; i++ ) { pipeline.zadd(zsetName, r.nextInt(), "value_"+i); } pipeline.sync(); final ArrayList<String> t1List = new ArrayList<String>(); final ArrayList<String> t2List = new ArrayList<String>(); Thread t1 = new Thread(new Runnable() { public void run() { try { Tuple pop = JedisUtil.popKeyFromZset(zsetName); while ( pop != null ) { t1List.add(pop.getElement()); pop = JedisUtil.popKeyFromZset(zsetName); } } catch (Exception e) { e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { public void run() { try { Tuple pop = JedisUtil.popKeyFromZset(zsetName); while ( pop != null ) { t2List.add(pop.getElement()); pop = JedisUtil.popKeyFromZset(zsetName); } } catch (Exception e) { e.printStackTrace(); } } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("t1List.size: " + t1List.size()); System.out.println("t2List.size: " + t2List.size()); assertEquals(max, t1List.size() + t2List.size()); for ( int i=0; i<t1List.size(); i++ ) { String element = t1List.get(i); assertFalse( t2List.contains(element) ); } } }