public class SimpleAtomicTransaction
extends BaseCorfuAppUtils
Consider again the code from org.corfudb.samples::HeloCorfu.java
:
Integer previous = map.get("a");
if (previous == null) {
System.out.println("This is the first time we were run!");
map.put("a", 1);
}
else {
map.put("a", ++previous);
System.out.println("This is the " + previous + " time we were run!");
}
If three program instances arrive at this code piece one after another, then the outcome would be:
"This is the first time we were run!"
"... 2 time ..."
"... 3 time"
What if we were to execute the above code concurrently? Try it.
Note that there is no need to worry about the atomicity of interleaved calls to individual Corfu-object methods,
e.g., `map.put` and `map.get`. All Corfu-object methods are guaranteed to be atomic
against multi-threaded programs and concurrent program instances.
However, there is no guarantee about the interleaving of `map.get` followed by `map.put`,
when invoked from concurrent program instances. Therefore, any of the following outputs are valid:
Output 1:
"... first time ..."
"... first time ..."
"... first time ..."
Output 2:
"... first time ..."
"... first time ..."
"... 2 time ..."
Output 3:
"... first time ..."
"... 2 time ..."
"... 2 time ..."
Output 4:
"... first time ..."
"... 2 time ..."
"... 3 time ..."
In order to enforce a consistent behavior, Corfu provides support for ACID transactions.
A transaction is a body of code wrapped with `TXBegin()` and `TXEnd()`.
For example, in the code below, we will wrap the code above with a transaction block:
corfuRuntime.getObjectsView().TXBegin();
Integer previous = map.get("a");
if (previous == null) {
System.out.println("This is the first time we were run!");
map.put("a", 1);
}
else {
map.put("a", ++previous);
System.out.println("This is the " + previous + " time we were run!");
}
corfuRuntime.getObjectsView.TXEnd();
If we were to run three instances of this program concurrently, we would guarantee
a **serializable** execution order. The only valid output would be
"... first time ..."
"... 2 time ..."
"... 3 time ..."
Created by dalia on 12/30/16.