1. /*
  2. * Copyright 2002-2004 The Apache Software Foundation
  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. *
  16. */
  17. package org.apache.tools.ant.util;
  18. import java.util.Enumeration;
  19. import java.util.Vector;
  20. /**
  21. * Generalization of <code>ExecuteWatchdog</code>
  22. *
  23. * @since Ant 1.5
  24. *
  25. * @see org.apache.tools.ant.taskdefs.ExecuteWatchdog
  26. *
  27. */
  28. public class Watchdog implements Runnable {
  29. private Vector observers = new Vector(1);
  30. private long timeout = -1;
  31. private boolean stopped = false;
  32. public Watchdog(long timeout) {
  33. if (timeout < 1) {
  34. throw new IllegalArgumentException("timeout lesser than 1.");
  35. }
  36. this.timeout = timeout;
  37. }
  38. public void addTimeoutObserver(TimeoutObserver to) {
  39. observers.addElement(to);
  40. }
  41. public void removeTimeoutObserver(TimeoutObserver to) {
  42. observers.removeElement(to);
  43. }
  44. protected final void fireTimeoutOccured() {
  45. Enumeration e = observers.elements();
  46. while (e.hasMoreElements()) {
  47. ((TimeoutObserver) e.nextElement()).timeoutOccured(this);
  48. }
  49. }
  50. public synchronized void start() {
  51. stopped = false;
  52. Thread t = new Thread(this, "WATCHDOG");
  53. t.setDaemon(true);
  54. t.start();
  55. }
  56. public synchronized void stop() {
  57. stopped = true;
  58. notifyAll();
  59. }
  60. public synchronized void run() {
  61. final long until = System.currentTimeMillis() + timeout;
  62. long now;
  63. while (!stopped && until > (now = System.currentTimeMillis())) {
  64. try {
  65. wait(until - now);
  66. } catch (InterruptedException e) {
  67. }
  68. }
  69. if (!stopped) {
  70. fireTimeoutOccured();
  71. }
  72. }
  73. }