1 24 25 package org.objectweb.cjdbc.controller.scheduler.schema; 26 27 import java.util.ArrayList ; 28 29 import org.objectweb.cjdbc.common.sql.AbstractRequest; 30 31 40 public class TransactionExclusiveLock 41 { 42 private boolean isLocked = false; 43 44 45 private long locker; 46 47 48 private ArrayList waitingList = new ArrayList (); 49 50 54 private class WaitingListElement 55 { 56 57 Thread thread; 58 59 60 long transactionId; 61 62 68 WaitingListElement(Thread thread, long transactionId) 69 { 70 this.thread = thread; 71 this.transactionId = transactionId; 72 } 73 74 79 public long getTransactionId() 80 { 81 return transactionId; 82 } 83 84 89 public Thread getThread() 90 { 91 return thread; 92 } 93 } 94 95 107 public boolean acquire(AbstractRequest request) 108 { 109 long tid = request.getTransactionId(); 110 111 synchronized (Thread.currentThread()) 112 { 113 WaitingListElement wle = null; 114 synchronized (this) 115 { 116 if (!isLocked) 117 { locker = tid; 119 isLocked = true; 120 return true; 121 } 122 else 123 { 124 if ((!request.isAutoCommit()) && (locker == tid)) 125 return true; else 127 { wle = new WaitingListElement(Thread.currentThread(), tid); 129 waitingList.add(wle); 130 } 131 } 132 } 133 try 135 { 136 int timeout = request.getTimeout(); 137 if (timeout == 0) 138 { 139 Thread.currentThread().wait(); return true; 142 } 143 else 144 { long start = System.currentTimeMillis(); 146 long lTimeout = timeout * 1000; 148 Thread.currentThread().wait(lTimeout); 149 long end = System.currentTimeMillis(); 150 int remaining = (int) (lTimeout - (end - start)); 151 if (remaining > 0) 152 { request.setTimeout(remaining); 154 return true; 156 } 157 else 158 { synchronized (this) 160 { 161 int idx = waitingList.indexOf(wle); 162 if (idx == -1) 163 release(); 166 else 167 waitingList.remove(idx); 168 } 169 return false; 170 } 171 } 172 } 173 catch (InterruptedException ie) 174 { 175 synchronized (this) 176 { waitingList.remove(Thread.currentThread()); 178 } 179 return false; 180 } 181 } 182 } 183 184 189 public synchronized void release() 190 { 191 while (!waitingList.isEmpty()) 192 { 193 WaitingListElement e = (WaitingListElement) waitingList.remove(0); 195 Thread thread = e.getThread(); 196 locker = e.getTransactionId(); 197 synchronized (thread) 198 { 199 thread.notify(); 200 return; 202 } 203 } 204 isLocked = false; 205 } 206 207 212 public boolean isLocked() 213 { 214 return isLocked; 215 } 216 217 223 public long getLocker() 224 { 225 return locker; 226 } 227 228 233 public ArrayList getWaitingList() 234 { 235 return waitingList; 236 } 237 238 245 public synchronized boolean isWaiting(long transactionId) 246 { 247 WaitingListElement e; 248 int size = waitingList.size(); 249 for (int i = 0; i < size; i++) 250 { 251 e = (WaitingListElement) waitingList.get(i); 252 if (e.getTransactionId() == transactionId) 253 return true; 254 } 255 return false; 256 } 257 } | Popular Tags |