/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package buzzerproxy; import java.io.IOException; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * The Timer class allows a graceful exit when an application * is stalled due to a networking timeout. Once the timer is * set, it must be cleared via the reset() method, or the * timeout() method is called. *
* The timeout length is customizable, by changing the 'length' * property, or through the constructor. The length represents * the length of the timer in milliseconds. * * @version 1.0 * @author David Reilly * @see http://www.javacoffeebreak.com/articles/network_timeouts/ */ public class Timer extends Thread { /** Rate at which timer is checked */ protected int m_rate = 100; /** Length of timeout */ private int m_length; /** Time elapsed */ private int m_elapsed; private Socket client; public boolean isTimeout = false; /** * Creates a timer of a specified length * @param length Length of time before timeout occurs */ public Timer(int length, Socket client) { if (client == null || !(client instanceof Socket)) { System.err.println("Client is null"); System.exit(1); } // Assign to member variable m_length = length; // Set time elapsed m_elapsed = 0; } /** Resets the timer back to zero */ public synchronized void reset() { m_elapsed = 0; } /** Performs timer specific code */ public void run() { // Keep looping for (;;) { // Put the timer to sleep try { Thread.sleep(m_rate); } catch (InterruptedException ioe) { continue; } // Use 'synchronized' to prevent conflicts synchronized (this) { // Increment time remaining m_elapsed += m_rate; // Check to see if the time has been exceeded if (m_elapsed > m_length) { isTimeout = true; // Trigger a timeout // timeout(); } // if (m_elapsed > m_length) { } // synchronized (this) { } // for (;;) { } // public void run() { // Override this to provide custom functionality public void timeout() { System.err.println("Network timeout occurred.... terminating"); //System.exit(1); try { System.err.println("Server closing client Socket"); client.close(); try { this.join(); // System.exit(1); } catch (InterruptedException ex) { Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex); } catch (NullPointerException n) { Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, n); } } // public void timeout() { } // Timer extends Thread