1 21 22 package org.armedbear.j; 23 24 public final class Mutex 25 { 26 private boolean inUse; 27 28 public final boolean isInUse() 29 { 30 return inUse; 31 } 32 33 public void acquire() throws InterruptedException 34 { 35 if (Thread.interrupted()) 36 throw new InterruptedException (); 37 synchronized(this) { 38 try { 39 while (inUse) 40 wait(); 41 inUse = true; 42 } 43 catch (InterruptedException e) { 44 notify(); 45 throw e; 46 } 47 } 48 } 49 50 public synchronized void release() 51 { 52 if (inUse) { 53 inUse = false; 54 notify(); 55 } else 56 Debug.bug("Mutex.release() mutex not in use!"); 57 } 58 59 public boolean attempt() throws InterruptedException 60 { 61 return attempt(0); 62 } 63 64 public boolean attempt(long msecs) throws InterruptedException 65 { 66 if (Thread.interrupted()) 67 throw new InterruptedException (); 68 synchronized(this) { 69 if (!inUse) { 70 inUse = true; 71 return true; 72 } else if (msecs <= 0) { 73 return false; 74 } else { 75 long waitTime = msecs; 76 long start = System.currentTimeMillis(); 77 try { 78 for (;;) { 79 wait(waitTime); 80 if (!inUse) { 81 inUse = true; 82 return true; 83 } else { 84 waitTime = msecs - (System.currentTimeMillis() - start); 85 if (waitTime <= 0) 86 return false; 87 } 88 } 89 } 90 catch (InterruptedException e) { 91 notify(); 92 throw e; 93 } 94 } 95 } 96 } 97 } 98 | Popular Tags |