1 23 24 package com.sun.enterprise.admin.common.domains.registry; 25 26 import java.io.RandomAccessFile ; 27 import java.lang.ClassNotFoundException ; 28 import java.io.IOException ; 29 import java.io.ObjectInputStream ; 30 import java.nio.channels.FileChannel ; 31 import java.nio.channels.FileLock ; 32 import java.io.FileInputStream ; 33 import java.io.EOFException ; 34 35 36 class Unlocked implements LockingStore 37 { 38 39 private PersistentStore storeImpl; 40 41 Unlocked(PersistentStore s){ 42 if (s == null) { 43 throw new NullPointerException ("store is null"); 44 } 45 46 storeImpl = s; 47 } 48 49 public synchronized Object readObject() throws IOException , TimeoutException, ClassNotFoundException { 50 ObjectInputStream in = null; 51 Object o = null; 52 try{ 53 in = getIn(); 54 o = (in != null ? in.readObject() : null) ; 55 } 56 catch (EOFException e){ 57 o = null; } 59 finally { 60 if (in != null) { 61 in.close(); 62 } 63 } 64 return o; 65 } 66 67 public long lastModified(){ return 0L ;} 68 public void unlock(){} 69 70 71 public void writeObject(Object o) throws IllegalStateException , IOException , TimeoutException { 72 throw new IllegalStateException ("Unlocked state - writeObject() not allowed"); 73 74 } 75 76 public void lock() throws TimeoutException, IOException { 77 final RandomAccessFile raf = new RandomAccessFile (storeImpl.getLock(), 78 "rws"); 79 getWriteLock(raf.getChannel()); 80 storeImpl.setState(new Locked(storeImpl, raf)); 81 } 82 83 private ObjectInputStream getIn() throws IOException { 84 final FileInputStream fis = new FileInputStream (storeImpl.getStore()); 85 getReadLock(fis.getChannel()); 86 if (fis.available() > 0){ 87 return new ObjectInputStream (fis); 88 } else { 89 fis.close(); 90 return null; 91 } 92 } 93 94 private FileLock getReadLock(FileChannel ch) throws TimeoutException, IOException { 95 return obtainLock(ch, true); 96 } 97 98 101 private FileLock getWriteLock(FileChannel ch) throws TimeoutException, IOException { 102 return obtainLock(ch, false); 103 } 104 105 private FileLock obtainLock(FileChannel channel, boolean shared) throws TimeoutException, IOException { 106 FileLock lock = null; 107 int attempts = 0; 108 try{ 109 110 while ((lock = channel.tryLock(0L, 0x7fffffff, shared)) == null && attempts++ < ATTEMPTS){ 111 Thread.currentThread().sleep(TIMEOUT); 112 } 113 } 114 catch (InterruptedException e){ 115 throw new TimeoutException(); 116 } 117 118 if (lock == null) { 119 throw new TimeoutException(); 120 } 121 return lock; 122 } 123 124 private static final int TIMEOUT = 3; 128 129 private static final int ATTEMPTS = 50; 131 132 } 133 134 135 136 | Popular Tags |