Index: src/main/java/com/sun/grizzly/jruby/RailsAdapter.java =================================================================== --- src/main/java/com/sun/grizzly/jruby/RailsAdapter.java (revision 251) +++ src/main/java/com/sun/grizzly/jruby/RailsAdapter.java (working copy) @@ -52,6 +52,7 @@ import org.jruby.RubyException; import org.jruby.RubyIO; import org.jruby.RubyHash; +import org.jruby.RubyThread; import org.jruby.exceptions.RaiseException; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.runtime.builtin.IRubyObject; @@ -59,9 +60,9 @@ import java.io.IOException; import java.io.OutputStream; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.Map; import java.util.HashMap; +import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; @@ -72,6 +73,7 @@ * @author Jean-Francois Arcand * @author Pramod Gopinath * @author Vivek Pandey + * @author Peter Williams */ public class RailsAdapter extends GrizzlyAdapter { @@ -198,9 +200,34 @@ } } + private final Map> threadMaps = + new HashMap>(); + private RubyThread getContextThread(Ruby runtime) { + RubyThread contextThread = null; + synchronized (threadMaps) { + WeakHashMap threadMap = threadMaps.get(runtime); + if(threadMap != null) { + contextThread = threadMap.get(Thread.currentThread()); + } else { + threadMap = new WeakHashMap(); + threadMaps.put(runtime, threadMap); + } + + if(contextThread == null) { + contextThread = RubyThread.adopt(runtime.getThread(), Thread.currentThread()); + threadMap.put(Thread.currentThread(), contextThread); + } + } + return contextThread; + } + private void dispatchRailsRequest(Ruby runtime, GrizzlyRequest req, GrizzlyResponse res) throws IOException { + RubyThread oldContext = runtime.getThreadService().getMainThread(); try { + RubyThread context = getContextThread(runtime); + runtime.getThreadService().setMainThread(context); + OutputStream os = res.getOutputStream(); RubyIO iObj = new RubyIO(runtime, req.getInputStream()); @@ -219,6 +246,8 @@ RubyException exception = e.getException(); exception.printBacktrace(System.err); throw e; + } finally { + runtime.getThreadService().setMainThread(oldContext); } }