Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 package org.ros.concurrent;
00018
00019 import com.google.common.base.Preconditions;
00020
00021 import java.util.concurrent.ExecutorService;
00022
00028 public abstract class CancellableLoop implements Runnable {
00029
00030 private final Object mutex;
00031
00035 private boolean ranOnce = false;
00036
00040 private Thread thread;
00041
00042 public CancellableLoop() {
00043 mutex = new Object();
00044 }
00045
00046 @Override
00047 public void run() {
00048 synchronized (mutex) {
00049 Preconditions.checkState(!ranOnce, "CancellableLoops cannot be restarted.");
00050 ranOnce = true;
00051 thread = Thread.currentThread();
00052 }
00053 try {
00054 setup();
00055 while (!thread.isInterrupted()) {
00056 loop();
00057 }
00058 } catch (InterruptedException e) {
00059 handleInterruptedException(e);
00060 } finally {
00061 thread = null;
00062 }
00063 }
00064
00069 protected void setup() {
00070 }
00071
00077 protected abstract void loop() throws InterruptedException;
00078
00082 protected void handleInterruptedException(InterruptedException e) {
00083 }
00084
00088 public void cancel() {
00089 if (thread != null) {
00090 thread.interrupt();
00091 }
00092 }
00093
00097 public boolean isRunning() {
00098 return thread != null && !thread.isInterrupted();
00099 }
00100 }