CancellableLoop.java
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2011 Google Inc.
00003  * 
00004  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
00005  * use this file except in compliance with the License. You may obtain a copy of
00006  * the License at
00007  * 
00008  * http://www.apache.org/licenses/LICENSE-2.0
00009  * 
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
00012  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
00013  * License for the specific language governing permissions and limitations under
00014  * the License.
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 }


rosjava_core
Author(s):
autogenerated on Wed Aug 26 2015 16:06:49