Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created March 6, 2011 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/857642 to your computer and use it in GitHub Desktop.
Save yokolet/857642 to your computer and use it in GitHub Desktop.
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
Copy link

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