3
 protected void waitAndSweep(String symbol) {
    try { 
      long sweepTime = symbolInfo.getSweepTime(symbol);
      long timeSinceLastSweep = System.currentTimeMillis() - sweepTime;
      long waitTime = timeSinceLastSweep >= getInterval() ? 0 : getInterval() - timeSinceLastSweep;
      logTradeEvent("waitAndSweep", symbol, "waittime: " + waitTime);
      if (waitTime > 0){
          Thread.sleep(waitTime);  
      }
      callSweep(symbol);
    }catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }catch (Exception e) {
      logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
          "Exception caught...", e);
    }
  }

While it is sleeping (Thread.sleep), How to interrupt this thread so that it comes out of waitandSweep method?

private void replace(){
// interrupt the thread;
// call waitandsweep again here;
waitandsweep(symbol)
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276

3 Answers3

4

Using wait() instead of sleep() allows you to wake up the thread via notify(), see e.g. Difference between wait() and sleep()

Community
  • 1
  • 1
Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
1

Keep a reference to the thread when you start it, and call Thread#interrupt on that reference. If the thread is sleeping the interruption will cause the sleep method to cut its sleep short and throw InterruptedException; if the thread is not sleeping then the interrupted flag will be set.

I have an example of interrupting a thread in this answer.

Using wait instead of sleep would mean you'd have to introduce a shared lock and a condition variable. The waiting thread would have to acquire that lock, then wait in a loop, checking the condition variable.

The condition variable and loop are required for several reasons:

1) A thread can return from waiting without having received a notification (the "spurious wakeup"), and

2) the notification is made while the thread doesn't have the lock, and there is no telling whether the state will still be the same as the state that caused the notification once the thread manages to re-acquire the lock

In this case it seems like a lot less trouble to use interruption here.

Community
  • 1
  • 1
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
0

You can use an ArrayBlockingQueue and use poll(long, java.util.concurrent.TimeUnit).

All you need then is to wake up the the tread, post something to the queue.

Please do not attempt to use wait/notify as there are many edge cases where that mechanism fails. For example, if a notify happens just after the wait times out, will the next wait immediately finish? Using a BlockingQueue allows you to drain it at appropriate times.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213