Created
April 28, 2012 05:56
-
-
Save anonymous/2516410 to your computer and use it in GitHub Desktop.
ScalaSTM waiting example in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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