Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import java.util.Map;
import org.jruby.Ruby;
import org.jruby.embed.LocalContextScope;
import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.ScriptingContainer;
public class TransientThreadsafe {
private TransientThreadsafe() {
ScriptingContainer container =
new ScriptingContainer(LocalContextScope.THREADSAFE, LocalVariableBehavior.TRANSIENT);
Runner runner1 = new Runner(container);
Runner runner2 = new Runner(container);
new Thread(runner1, "Runner-1").start();
new Thread(runner2, "Runner-2").start();
runner1.getVarMap().put("$tmp", "Atlanta");
runner2.getVarMap().put("$tmp", "Los Angeles");
}
public static void main(String[] args) {
new TransientThreadsafe();
}
class Runner implements Runnable {
ScriptingContainer container;
Map varMap = null;
Runner(ScriptingContainer container) {
this.container = container;
}
@Override
public void run() {
varMap = container.getProvider().getVarMap();
while (varMap == null || varMap.get("$tmp") == null) {
try {
Thread.currentThread().sleep(1000L);
} catch (InterruptedException e) {
// no-op
}
}
container.runScriptlet("puts \"" + Thread.currentThread().getName() + " ran in #{$tmp}\"");
}
Map getVarMap() {
while(varMap == null) {
try {
Thread.currentThread().sleep(1000L);
} catch (InterruptedException e) {
// no-op
}
}
return varMap;
}
}
}

newacct commented May 6, 2011

Thread.currentThread().sleep(1000L); should just be written as Thread.sleep(1000L); since sleep() is a static method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment