1 17 18 21 package org.quartz.impl.jdbcjobstore; 22 23 import java.sql.Connection ; 24 import java.util.HashSet ; 25 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 29 36 public class SimpleSemaphore implements Semaphore { 37 38 45 46 ThreadLocal lockOwners = new ThreadLocal (); 47 48 HashSet locks = new HashSet (); 49 50 private final Log log = LogFactory.getLog(getClass()); 51 52 59 60 protected Log getLog() { 61 return log; 62 } 63 64 private HashSet getThreadLocks() { 65 HashSet threadLocks = (HashSet ) lockOwners.get(); 66 if (threadLocks == null) { 67 threadLocks = new HashSet (); 68 lockOwners.set(threadLocks); 69 } 70 return threadLocks; 71 } 72 73 79 public synchronized boolean obtainLock(Connection conn, String lockName) { 80 81 lockName = lockName.intern(); 82 83 Log log = getLog(); 84 85 if(log.isDebugEnabled()) { 86 log.debug( 87 "Lock '" + lockName + "' is desired by: " 88 + Thread.currentThread().getName()); 89 } 90 91 if (!isLockOwner(conn, lockName)) { 92 if(log.isDebugEnabled()) { 93 log.debug( 94 "Lock '" + lockName + "' is being obtained: " 95 + Thread.currentThread().getName()); 96 } 97 while (locks.contains(lockName)) { 98 try { 99 this.wait(); 100 } catch (InterruptedException ie) { 101 if(log.isDebugEnabled()) { 102 log.debug( 103 "Lock '" + lockName + "' was not obtained by: " 104 + Thread.currentThread().getName()); 105 } 106 } 107 } 108 109 if(log.isDebugEnabled()) { 110 log.debug( 111 "Lock '" + lockName + "' given to: " 112 + Thread.currentThread().getName()); 113 } 114 getThreadLocks().add(lockName); 115 locks.add(lockName); 116 } else if(log.isDebugEnabled()) { 117 log.debug( 118 "Lock '" + lockName + "' already owned by: " 119 + Thread.currentThread().getName() 120 + " -- but not owner!", 121 new Exception ("stack-trace of wrongful returner")); 122 } 123 124 return true; 125 } 126 127 131 public synchronized void releaseLock(Connection conn, String lockName) { 132 133 lockName = lockName.intern(); 134 135 if (isLockOwner(conn, lockName)) { 136 if(getLog().isDebugEnabled()) { 137 getLog().debug( 138 "Lock '" + lockName + "' retuned by: " 139 + Thread.currentThread().getName()); 140 } 141 getThreadLocks().remove(lockName); 142 locks.remove(lockName); 143 this.notify(); 144 } else if (getLog().isDebugEnabled()) { 145 getLog().debug( 146 "Lock '" + lockName + "' attempt to retun by: " 147 + Thread.currentThread().getName() 148 + " -- but not owner!", 149 new Exception ("stack-trace of wrongful returner")); 150 } 151 } 152 153 157 public synchronized boolean isLockOwner(Connection conn, String lockName) { 158 159 lockName = lockName.intern(); 160 161 return getThreadLocks().contains(lockName); 162 } 163 164 167 public boolean requiresConnection() { 168 return false; 169 } 170 } 171 | Popular Tags |