1

Possible Duplicate:
Start/Suspend/Resume/Suspend … a method invoked by other class

I want to implement an Anytime k-NN classifier but I cannot find a way to call the "classify(...)" method for a specific amount of time, suspend it, get the available results before the method was suspended, resume the method for a specific amount of time, suspend it, get the available results before the method was suspended, and so on...

Thanks in advance!

Community
  • 1
  • 1
pm3310
  • 119
  • 1
  • 2
  • 9
  • Neither can I. Unless the classify() call periodically calls back for the storage of results or at some suitable checkpoint, you won't be able to get at the execution to pause it, (eg. by having it check a 'pause' flag and, if set, signal a 'paused' event and then wait on a 'resume' event). – Martin James Jul 21 '12 at 14:58
  • @Martin James - I don't really agree with you. You can of course pause a thread or even stop it completely without something like ckeck-points or flags. If this is a good idea or not is another question, but it could be a suitable idea. I mean, a debugger is doing something similar, it stops somewhere and let you see all variables. How ever, I agree with you that calling a storage and display it after each iteration would be a good approach. – Thomas Uhrig Jul 21 '12 at 15:29
  • @ThomasUhrig - you are right, of course. I kinda skipped over the 'issues' with suspending/aborting the thread while it may hold explicit or implicit locks on system resources. Debuggers and complete process termination aside, the OP should make some loop accessible outside the call - some outer loop maybe, where the data is in some incompletely processed, but 'sorta-valid' state. – Martin James Jul 21 '12 at 17:01

1 Answers1

0

I posted a PauseableThread on here recently.

You can implement a pause using a ReadWriteLock. If you momentarily grab a write lock on it every time you hit an opportunity to pause then you just need the pauser to grab a read lock to pause you.

  // The lock.
  private final ReadWriteLock pause = new ReentrantReadWriteLock();

  // Block if pause has been called without a matching resume.
  private void blockIfPaused() throws InterruptedException {
    try {
      // Grab a write lock. Will block if a read lock has been taken.
      pause.writeLock().lockInterruptibly();
    } finally {
      // Release the lock immediately to avoid blocking when pause is called.
      pause.writeLock().unlock();
    }
  }

  // Pause the work. NB: MUST be balanced by a resume.
  public void pause() {
    // We can wait for a lock here.
    pause.readLock().lock();
  }

  // Resume the work. NB: MUST be balanced by a pause.
  public void resume() {
    // Release the lock.
    pause.readLock().unlock();
  }
Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213