1 26 27 28 package org.objectweb.mobilitools.util.thread; 29 30 31 40 public class ShutdownLock 41 { 42 volatile int in = 0; 43 volatile Thread thread = null; 44 volatile boolean shutdown = false; 45 boolean trace = false; 46 String name = null; 47 48 49 52 public ShutdownLock() 53 { 54 } 55 56 57 61 public ShutdownLock(String lockName) 62 { 63 name = lockName; 64 trace = true; 65 } 66 67 68 73 synchronized public void in() 74 throws ShutdownException 75 { 76 if (shutdown && Thread.currentThread() != thread) 77 { 78 throw new ShutdownException(); 79 } 80 ++in; 81 if (trace) 82 { 83 System.out.println(Thread.currentThread() + " entered ShutdownLock " + name + " (=" + in + ")."); 84 } 85 } 86 87 88 92 synchronized public void out() 93 { 94 if (--in == 0) 95 { 96 if (trace) 97 { 98 System.out.println("ShutdownLock " + name + " is released."); 99 } 100 if (shutdown && Thread.currentThread() != thread) 101 { 102 notify(); 103 } 104 } 105 else if (trace) 106 { 107 System.out.println("ShutdownLock " + name + " = " + in + "."); 108 } 109 } 110 111 112 118 synchronized public void shutdown() 119 throws ShutdownException 120 { 121 if (shutdown) 122 { 123 throw new ShutdownException(); 124 } 125 shutdown = true; 126 thread = Thread.currentThread(); 127 if (in > 0) 128 { 129 if (trace) 130 { 131 System.out.println("ShutdownLock " + name + " shutdown is pending for " + thread); 132 } 133 try 134 { 135 wait(); 136 } 137 catch (InterruptedException e) 138 { 139 e.printStackTrace(); 140 } 141 } 142 if (trace) 143 { 144 System.out.println("ShutdownLock " + name + " is shutdown."); 145 } 146 } 147 148 149 152 public class ShutdownException extends Exception 153 { 154 public ShutdownException() 155 { 156 } 157 public ShutdownException(String msg) 158 { 159 super(msg); 160 } 161 } 162 } 163 | Popular Tags |