Skip to content

Instantly share code, notes, and snippets.

@ruskotron
Created August 13, 2014 11:32
Show Gist options
  • Save ruskotron/2ba7a23f3f29db9ab879 to your computer and use it in GitHub Desktop.
Save ruskotron/2ba7a23f3f29db9ab879 to your computer and use it in GitHub Desktop.
interface Resource {
void monopolise() throws InterruptedException;
}
public class Interrupts implements Runnable {
private final MyResources myRes;
public Interrupts(MyResources myRes) {
this.myRes = myRes;
}
private void timeConsumingStuff() throws InterruptedException {
/* Allocate some resources */
Resource res = myRes.getResource();
try {
/* Perform some indeterminate-time operation on res */
res.monopolise();
/* Do some other bits and pieces */
} finally {
myRes.cleanup(res);
}
}
public void run() {
try {
/* Use `isInterrupted` to idempotently interrogate interrupted status */
while (!Thread.currentThread().isInterrupted()) {
timeConsumingStuff
}
} catch (InterruptedException consumed) {
/* Restore the interrupted status */
Thread.currentThread().interrupt();
}
}
public void cancel() {
interrupt();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment