1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16package com.replica.replicaisland; 17 18import java.util.concurrent.Semaphore; 19import java.util.concurrent.TimeUnit; 20 21import android.util.Log; 22 23import junit.framework.Assert; 24 25/** 26 * class for checking if rendering function is alive or not. 27 * panic if watch-dog is not reset over certain amount of time 28 */ 29public class RenderingWatchDog implements Runnable { 30 /** panic if watch-dog is not reset over this amount of time */ 31 private static final long DEFAULT_TIMEOUT_IN_MSECS = 10 * 1000; 32 private static final String TAG = "RenderingWatchDog"; 33 private Thread mThread; 34 private Semaphore mSemaphore; 35 private volatile boolean mStopRequested; 36 private final long mTimeoutInMilliSecs; 37 38 public RenderingWatchDog() { 39 this(DEFAULT_TIMEOUT_IN_MSECS); 40 } 41 42 public RenderingWatchDog(long timeoutInMilliSecs) { 43 mTimeoutInMilliSecs = timeoutInMilliSecs; 44 } 45 46 /** start watch-dog */ 47 public void start() { 48 Log.i(TAG, "start"); 49 mStopRequested = false; 50 mSemaphore = new Semaphore(0); 51 mThread = new Thread(this); 52 mThread.start(); 53 } 54 55 /** stop watch-dog */ 56 public void stop() { 57 Log.i(TAG, "stop"); 58 if (mThread == null) { 59 return; // already finished 60 } 61 mStopRequested = true; 62 mSemaphore.release(); 63 try { 64 mThread.join(); 65 } catch (InterruptedException e) { 66 // ignore 67 } 68 mThread = null; 69 mSemaphore = null; 70 } 71 72 /** resets watch-dog, thus prevent it from panic */ 73 public void reset() { 74 if (!mStopRequested) { // stop requested, but rendering still on-going 75 mSemaphore.release(); 76 } 77 } 78 79 @Override 80 public void run() { 81 while (!mStopRequested) { 82 try { 83 Assert.assertTrue("Watchdog timed-out", 84 mSemaphore.tryAcquire(mTimeoutInMilliSecs, TimeUnit.MILLISECONDS)); 85 } catch (InterruptedException e) { 86 // this thread will not be interrupted, 87 // but if it happens, just check the exit condition. 88 } 89 } 90 } 91} 92