1 package org.apache.lucene.store; 2 3 18 19 import org.apache.lucene.index.IndexWriter; 20 21 import java.io.IOException ; 22 23 36 public abstract class Lock { 37 public static long LOCK_POLL_INTERVAL = 1000; 38 39 43 public abstract boolean obtain() throws IOException ; 44 45 52 public boolean obtain(long lockWaitTimeout) throws IOException { 53 boolean locked = obtain(); 54 int maxSleepCount = (int)(lockWaitTimeout / LOCK_POLL_INTERVAL); 55 int sleepCount = 0; 56 while (!locked) { 57 if (sleepCount++ == maxSleepCount) { 58 throw new IOException ("Lock obtain timed out: " + this.toString()); 59 } 60 try { 61 Thread.sleep(LOCK_POLL_INTERVAL); 62 } catch (InterruptedException e) { 63 throw new IOException (e.toString()); 64 } 65 locked = obtain(); 66 } 67 return locked; 68 } 69 70 71 public abstract void release(); 72 73 75 public abstract boolean isLocked(); 76 77 78 79 public abstract static class With { 80 private Lock lock; 81 private long lockWaitTimeout; 82 83 87 public With(Lock lock) 88 { 89 this(lock, IndexWriter.COMMIT_LOCK_TIMEOUT); 90 } 91 92 93 public With(Lock lock, long lockWaitTimeout) { 94 this.lock = lock; 95 this.lockWaitTimeout = lockWaitTimeout; 96 } 97 98 99 protected abstract Object doBody() throws IOException ; 100 101 105 public Object run() throws IOException { 106 boolean locked = false; 107 try { 108 locked = lock.obtain(lockWaitTimeout); 109 return doBody(); 110 } finally { 111 if (locked) 112 lock.release(); 113 } 114 } 115 } 116 117 } 118 | Popular Tags |