Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 3 additions & 16 deletions core/src/main/java/org/jruby/RubyKernel.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import jnr.constants.platform.Errno;
import jnr.posix.POSIX;
Expand Down Expand Up @@ -899,23 +898,11 @@ private static RubyFixnum sleepCommon(ThreadContext context, long nanoseconds) {
final long startTime = System.nanoTime();
final RubyThread rubyThread = context.getThread();

boolean interrupted = false;
try {
// Spurious wakeup-loop
do {
long loopStartTime = System.nanoTime();
long milliseconds = TimeUnit.NANOSECONDS.toMillis(nanoseconds);
long remainingNanos = nanoseconds - TimeUnit.MILLISECONDS.toNanos(milliseconds);

if (!rubyThread.sleep(milliseconds, remainingNanos)) break;

nanoseconds -= (System.nanoTime() - loopStartTime);
} while (nanoseconds > 0);
rubyThread.sleepUntilWakeup(context, nanoseconds);
} catch (InterruptedException ie) {
// ignore; sleep gets interrupted
interrupted = true;
} finally {
if (interrupted) Thread.currentThread().interrupt();
// A Java interrupt ends the sleep. Keep the flag set for the caller.
Thread.currentThread().interrupt();
}

return asFixnum(context, Math.round((System.nanoTime() - startTime) / 1_000_000_000.0));
Expand Down
58 changes: 55 additions & 3 deletions core/src/main/java/org/jruby/RubyThread.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
import com.headius.backport9.stack.StackWalker;
import org.jcodings.Encoding;
import org.joni.Matcher;
import org.jruby.anno.CRuby;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.api.Create;
Expand Down Expand Up @@ -1616,6 +1617,24 @@ public boolean sleep(long milliseconds, long nanoseconds) throws InterruptedExce
}
}

/**
* Sleep for Kernel#sleep. Only the deadline or Thread#wakeup ends the sleep. An interrupt masked by
* handle_interrupt wakes the thread, but it goes back to sleep.
*
* @param context the current context
* @param nanoseconds time to sleep. Zero sleeps until woken.
*/
public void sleepUntilWakeup(ThreadContext context, long nanoseconds) throws InterruptedException {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit-pick: not sure whether to expose this on a core clas - usually it's best to hide and be mindful whether we want things as public API, in this case:

Suggested change
public void sleepUntilWakeup(ThreadContext context, long nanoseconds) throws InterruptedException {
void sleepUntilWakeup(ThreadContext context, long nanoseconds) throws InterruptedException {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Don't expose until it's obviously needed as a public API.

sleepTask.nanoseconds = nanoseconds;
sleepTask.untilWakeup = true;
try {
executeTaskBlocking(context, null, sleepTask);
} finally {
sleepTask.untilWakeup = false;
sleepTask.semaphore.drainPermits();
}
}

public IRubyObject status() { // not used
return status(getRuntime().getCurrentContext());
}
Expand Down Expand Up @@ -1718,14 +1737,17 @@ public void wakeup() {
private static class SleepTask2 implements Task<Object, Long> {
final Semaphore semaphore = new Semaphore(1);
long nanoseconds;
boolean untilWakeup;
{semaphore.drainPermits();}

@Override
public Long run(ThreadContext context, Object data) throws InterruptedException {
long start = System.nanoTime();

try {
if (nanoseconds == 0) {
if (untilWakeup) {
sleepUntilWakeup(context, start);
} else if (nanoseconds == 0) {
semaphore.tryAcquire(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} else {
semaphore.tryAcquire(nanoseconds, TimeUnit.NANOSECONDS);
Expand All @@ -1737,6 +1759,28 @@ public Long run(ThreadContext context, Object data) throws InterruptedException
}
}

@CRuby(value = "sleep_hrtime", file = "thread.c")
@CRuby(value = "sleep_forever", file = "thread.c")
private void sleepUntilWakeup(ThreadContext context, long start) throws InterruptedException {
RubyThread thread = context.getThread();
while (true) {
if (nanoseconds == 0) {
semaphore.acquire();
} else {
long remaining = nanoseconds - (System.nanoTime() - start);
if (remaining <= 0) return;
if (!semaphore.tryAcquire(remaining, TimeUnit.NANOSECONDS)) return;
}
semaphore.drainPermits();

// Raise interrupts that are not masked. Masked ones leave the thread asleep.
context.blockingThreadPoll();

// Thread#wakeup sets the status to RUN
if (thread.getStatus() != Status.SLEEP) return;
}
}

@Override
public void wakeup(RubyThread thread, Object data) {
semaphore.release();
Expand Down Expand Up @@ -1775,6 +1819,7 @@ public <Data, Return> Return executeTask(ThreadContext context, Data data, Statu

private <Data, Return> Return executeTask(ThreadContext context, Data data, Status status, Task<Data, Return> task, boolean blocking) throws InterruptedException {
Status oldStatus = STATUS.get(this);
boolean raised = true;
try {
this.unblockArg = data;
this.unblockFunc = task;
Expand All @@ -1784,12 +1829,19 @@ private <Data, Return> Return executeTask(ThreadContext context, Data data, Stat

STATUS.set(this, status);

return task.run(context, data);
Return result = task.run(context, data);
raised = false;
return result;
} catch (InterruptedException ie) {
// Java interrupted the wait. Still check for Ruby interrupts below.
raised = false;
throw ie;
} finally {
STATUS.set(this, oldStatus);
this.unblockFunc = null;
this.unblockArg = null;
pollThreadEvents(context, blocking);
// Don't let the next pending interrupt replace an exception already on its way out
if (!raised) pollThreadEvents(context, blocking);
}
}

Expand Down
39 changes: 39 additions & 0 deletions spec/ruby/core/thread/handle_interrupt_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,45 @@ def make_handle_interrupt_thread(interrupt_config, blocking = true)
queue.pop.should == :second
end

it "defers an interrupt raised while the thread sleeps with a timeout" do
log = []
thread = Thread.new do
Thread.handle_interrupt(RuntimeError => :never) do
sleep 10
log << :slept
end
log << :not_reached
end
thread.report_on_exception = false

Thread.pass until thread.stop?
thread.raise "interrupt in sleep"
thread.join(0.1).should == nil
thread.wakeup

-> { thread.join }.should raise_error(RuntimeError, "interrupt in sleep")
log.should == [:slept]
end

it "defers Thread#kill while the thread sleeps without a timeout" do
log = []
thread = Thread.new do
Thread.handle_interrupt(Object => :never) do
sleep
log << :slept
end
log << :not_reached
end

Thread.pass until thread.stop?
thread.kill
thread.join(0.1).should == nil
thread.wakeup

thread.join.should == thread
log.should == [:slept]
end

it "runs pending interrupts at the end of the block, even if there was an exception raised in the block" do
executed = false
-> {
Expand Down
13 changes: 13 additions & 0 deletions spec/ruby/core/thread/raise_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,19 @@ def exception(*args)
[ScratchPad.recorded, @thr, []]
]
end

it "raises the exception in a thread waiting in Queue#pop even if Thread#kill follows" do
t = Thread.new do
Thread.current.report_on_exception = false
Queue.new.pop
end

ThreadSpecs.spin_until_sleeping(t)

t.raise "raised before kill"
t.kill
-> { t.join }.should raise_error(RuntimeError, "raised before kill")
end
end

describe "Thread#raise on a running thread" do
Expand Down
Loading