Skip to content

Instantly share code, notes, and snippets.

Created April 28, 2012 05:56
Show Gist options
  • Save anonymous/2516410 to your computer and use it in GitHub Desktop.
Save anonymous/2516410 to your computer and use it in GitHub Desktop.
ScalaSTM waiting example in Java
import scala.concurrent.stm.*;
import scala.concurrent.stm.japi.*;
public class a {
public static void retry() {
final InTxn txn = Txn.findCurrent(TxnUnknown$.MODULE$).get();
Txn.retry(txn);
}
public static void main(final String[] args) {
final Ref.View<Integer> x = STM.newRef(0);
// this thread will change x after 2 seconds
new Thread() {
public void run() {
System.out.println("bg thread sleeping");
try {
Thread.sleep(2000);
} catch (final InterruptedException ex) {
throw new RuntimeException("unexpected", ex);
}
System.out.println("changing x");
x.set(1);
}
}.start();
STM.atomic(new Runnable() {
public void run() {
if (x.get() == 0) {
// wait until x is non-zero
retry();
}
}
});
System.out.println("waiting finished");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment