001 /* 002 * $Id: TimeStatus.java 3203 2010-07-02 15:54:32Z kredel $ 003 */ 004 005 package edu.jas.kern; 006 007 import java.util.concurrent.Callable; 008 009 010 /** 011 * Run-time status, 012 * defines global status and handling for run time limits. 013 * @author Heinz Kredel 014 */ 015 016 public class TimeStatus { 017 018 019 /** 020 * Global status flag. 021 */ 022 private static boolean allowTime = false; 023 024 025 /** 026 * Global run-time limit in milliseconds. 027 */ 028 private static long limitTime = Long.MAX_VALUE; 029 030 031 /** 032 * Global run-time limit in milliseconds. 033 */ 034 private static long startTime = System.currentTimeMillis(); 035 036 037 /** 038 * Call back method. 039 * true means continue, false means throw exception. 040 */ 041 private static Callable<Boolean> callBack = null; 042 043 044 /** 045 * No public constructor. 046 */ 047 protected TimeStatus() { 048 } 049 050 051 /** 052 * isActive. 053 * @return true, if run-time interruption is active, else false. 054 */ 055 public static boolean isActive() { 056 return allowTime; 057 } 058 059 060 /** 061 * setAllow, 062 * set run-time interruption to allowed status. 063 */ 064 public static void setActive() { 065 allowTime = true; 066 } 067 068 069 /** 070 * setNotActive, 071 * set run-time interruption to not active status. 072 */ 073 public static void setNotActive() { 074 allowTime = false; 075 } 076 077 078 /** 079 * setLimit, 080 * set run-time limit in milliseconds. 081 */ 082 public static void setLimit(long t) { 083 limitTime = t; 084 } 085 086 087 /** 088 * Restart timer, 089 * set run-time to current time. 090 */ 091 public static void restart() { 092 startTime = System.currentTimeMillis(); 093 } 094 095 096 /** 097 * set call back, 098 * set the Callabe object. 099 */ 100 public static void setCallBack(Callable<Boolean> cb) { 101 callBack = cb; 102 } 103 104 105 /** 106 * Check for exceeded time, 107 * test if time has exceeded and throw an exception if so. 108 * @param msg the message to be send with the exception. 109 */ 110 public static void checkTime(String msg) { 111 if ( ! allowTime ) { 112 return; 113 } 114 if ( limitTime == Long.MAX_VALUE ) { 115 return; 116 } 117 long tt = (System.currentTimeMillis() - startTime - limitTime); 118 //System.out.println("tt = " + tt); 119 if ( tt <= 0L ) { 120 return; 121 } 122 if ( callBack != null ) { 123 try { 124 boolean t = callBack.call(); 125 if ( t ) { 126 return; 127 } 128 } catch ( Exception e ) { 129 } 130 } 131 if ( msg == null ) { 132 msg = ""; 133 } 134 throw new TimeExceededException(msg + " over time = " + tt); 135 } 136 137 }