1 /**
2 * .
3 * Copyright � 1999 Erich P G.
4 *
5 */
6
7 package autohit.utils;
8
9 /**
10 * A simple object monitor that can be used as a mutex.
11 *
12 * @author Erich P. Gatejen
13 * @version 1.0
14 * <i>Version History</i>
15 * <code>EPG - Initial - 15Jan99</code>
16 *
17 */
18 public class ObjectMonitor extends Object {
19
20 private int locked;
21
22
23 /**
24 * Default constructor. It will create the monitor that
25 * is unlocked.
26 */
27 public ObjectMonitor() {
28 this(1);
29 }
30
31 /**
32 * Contructor. Allows you to set the lock on creation.
33 * I recommend against using this one... I bet you
34 * get yourself deadlocked. :D
35 */
36 public ObjectMonitor(int lock) {
37 locked = lock;
38 }
39
40 /**
41 * Lock or unlock the monitor. Trying to lock an already
42 * locked monitor will block the thread until the owning
43 * thread unlocks it. More than one thread can be waiting
44 * for the lock. So, watchout for deadlock!
45 *
46 * @param lock true locks, false unlocks.
47 */
48 public synchronized void lock(boolean lock) {
49 if (lock) {
50 while (locked == 0) {
51 try {
52 wait();
53 } catch (InterruptedException e) { }
54 }
55 locked--;
56 } else {
57 locked++;
58 notify();
59 }
60 }
61
62 /**
63 * This is a syncronized notify. This way any thread can
64 * notify as the owner.
65 */
66 public synchronized void ownNotify() {
67 this.notify();
68 }
69
70 /**
71 * This is a syncronized notifyAll.
72 */
73 public synchronized void ownNotifyAll() {
74 this.notifyAll();
75 }
76
77 /**
78 * This is a syncronized wait. Interrupt exception is caught
79 * and discarded.
80 */
81 public synchronized void ownWait() {
82 try {
83 this.wait();
84 } catch (Exception e) { }
85 }
86
87 }
88
|