Fix a concurrency bug in Java queue example

firstItem() should be in the same transaction of clear()
This commit is contained in:
xmeng 2018-06-12 21:01:19 +01:00
parent bd9e416e8c
commit 8ae25bed5c
2 changed files with 16 additions and 18 deletions

View File

@ -81,19 +81,18 @@ The following is a simple implementation of the basic pattern:
// Remove the top element from the queue. // Remove the top element from the queue.
public static Object dequeue(TransactionContext tcx){ public static Object dequeue(TransactionContext tcx){
final KeyValue item = firstItem(tcx);
if(item == null){
return null;
}
// Remove from the top of the queue. // Remove from the top of the queue.
tcx.run((Transaction tr) -> { return tcx.run((Transaction tr) -> {
final KeyValue item = firstItem(tr);
if(item == null){
return null;
}
tr.clear(item.getKey()); tr.clear(item.getKey());
return null; // Return the old value.
return Tuple.fromBytes(item.getValue()).get(0);
}); });
// Return the old value.
return Tuple.fromBytes(item.getValue()).get(0);
} }
// Add an element to the queue. // Add an element to the queue.

View File

@ -44,21 +44,20 @@ public class MicroQueue {
// Remove the top element from the queue. // Remove the top element from the queue.
public static Object dequeue(TransactionContext tcx){ public static Object dequeue(TransactionContext tcx){
final KeyValue item = firstItem(tcx);
if(item == null){
return null;
}
// Remove from the top of the queue. // Remove from the top of the queue.
tcx.run(new Function<Transaction,Void>(){ return tcx.run(new Function<Transaction,Void>(){
public Void apply(Transaction tr){ public Void apply(Transaction tr){
final KeyValue item = firstItem(tr);
if(item == null){
return null;
}
tr.clear(item.getKey()); tr.clear(item.getKey());
return null; // Return the old value.
return Tuple.fromBytes(item.getValue()).get(0);
} }
}); });
// Return the old value.
return Tuple.fromBytes(item.getValue()).get(0);
} }
// Add an element to the queue. // Add an element to the queue.