/*
 * Java Network Programming, Second Edition
 * Merlin Hughes, Michael Shoffner, Derek Hamner
 * Manning Publications Company; ISBN 188477749X
 *
 * http://nitric.com/jnp/
 *
 * Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner;
 * all rights reserved; see license.txt for details.
 */

public class Alarm implements Runnable {
  public Alarm (int time, Alarmable target) {
    this (time, target, null);
  }

  protected Alarmable target;
  protected Object arg;
  protected int time;
  public Alarm (int time, Alarmable target, Object arg) {
    this.time = time;
    this.target = target;
    this.arg = arg;
  }

  protected Thread alarm;
  public synchronized void start () {
    if (alarm == null) {
      alarm = new Thread (this);
      alarm.start ();
    }
  }

  public synchronized void stop () {
    if (alarm != null) {
      alarm.interrupt ();
      alarm = null;
    }
  }

  public void run () {
    try {
      Thread.sleep (time);
      synchronized (this) {
        if (Thread.interrupted ())
          return;
        alarm = null;
      }
      target.alarmCall (arg);
    } catch (InterruptedException ignored) {
    }
  }
}
