Skip to content

Commit ea48751

Browse files
committed
Add sleep_interruptibly utility method to allow sleep and block threads on Java blocking abstractions
1 parent 74c4bf1 commit ea48751

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

ext/com/concurrent_ruby/ext/SynchronizationLibrary.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import org.jruby.RubyClass;
66
import org.jruby.RubyModule;
77
import org.jruby.RubyObject;
8+
import org.jruby.RubyThread;
89
import org.jruby.anno.JRubyClass;
910
import org.jruby.anno.JRubyMethod;
1011
import org.jruby.runtime.Block;
@@ -96,6 +97,14 @@ public void load(Ruby runtime, boolean wrap) throws IOException {
9697

9798
defineClass(runtime, synchronizationModule, "AbstractLockableObject", "JRubyLockableObject",
9899
JRubyLockableObject.class, JRUBY_LOCKABLE_OBJECT_ALLOCATOR);
100+
101+
defineClass(runtime, synchronizationModule, "Object", "JRuby",
102+
JRuby.class, new ObjectAllocator() {
103+
@Override
104+
public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
105+
return new JRuby(runtime, klazz);
106+
}
107+
});
99108
}
100109

101110
private RubyClass defineClass(
@@ -267,4 +276,29 @@ public IRubyObject nsBroadcast(ThreadContext context) {
267276
return this;
268277
}
269278
}
279+
280+
@JRubyClass(name = "JRuby")
281+
public static class JRuby extends RubyObject {
282+
public JRuby(Ruby runtime, RubyClass metaClass) {
283+
super(runtime, metaClass);
284+
}
285+
286+
@JRubyMethod(name = "sleep_interruptibly", visibility = Visibility.PUBLIC, module = true)
287+
public static IRubyObject sleepInterruptibly(ThreadContext context, IRubyObject receiver, Block block) {
288+
try {
289+
return context.getThread().executeTask(context, block,
290+
new RubyThread.Task<Block, IRubyObject>() {
291+
public IRubyObject run(ThreadContext context, Block block1) throws InterruptedException {
292+
return block1.call(context);
293+
}
294+
295+
public void wakeup(RubyThread thread, Block block1) {
296+
thread.getNativeThread().interrupt();
297+
}
298+
});
299+
} catch (InterruptedException e) {
300+
throw context.runtime.newThreadError("interrupted in Concurrent::Synchronization::JRuby.sleep_interruptibly");
301+
}
302+
}
303+
}
270304
}

0 commit comments

Comments
 (0)