Fix a concurrency bug in Java queue example
firstItem() should be in the same transaction of clear()
This commit is contained in:
parent
bd9e416e8c
commit
8ae25bed5c
|
@ -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.
|
||||||
|
|
|
@ -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.
|
||||||
|
|
Loading…
Reference in New Issue