dfc978ee85f6701db952bc33d8ffad67c30418c4
[vamsas.git] / src / org / vamsas / client / simpleclient / Lock.java
1 package org.vamsas.client.simpleclient;
2
3 import java.io.FileNotFoundException;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.RandomAccessFile;
7 import java.nio.channels.FileLock;
8
9 /**
10  * transient object representing a file lock
11  * This lock should hold for all processes interacting in a session.
12  * TODO: currently implemented for local filesystem style locking - need a fallback mechanism for systems without file locks.
13  * @author jimp
14  * 
15  */
16
17 public class Lock {
18   FileLock lock = null;
19   RandomAccessFile rafile=null;
20   /**
21    * creates a valid Lock (test with <method>isLocked</method>)
22    * if a lock could be obtained for <param>lockfile</param>
23    * @param lockfile
24    */
25   public Lock(java.io.File lockfile) {
26     // try and get a lock.
27     lock = null;
28     
29     try {
30       if (!lockfile.exists())
31         if (!lockfile.createNewFile()) {
32           return;
33         }
34       
35       lock = (rafile=new RandomAccessFile(lockfile,"rw")).getChannel().tryLock();
36       if (lock==null || !lock.isValid())
37         // failed to get lock. Close the file channel
38         rafile.getChannel().close();
39     } catch (FileNotFoundException e) {
40       System.err.println("Error! Couldn't create a lockfile at "
41           + lockfile.getAbsolutePath());
42       e.printStackTrace();
43     } catch (IOException e) {
44       System.err.println("Error! Problems with IO when creating a lock on "
45           + lockfile.getAbsolutePath());
46       e.printStackTrace();
47     }
48   }
49   
50   boolean isLocked() {
51     if (lock != null && lock.isValid()) {
52       return true;
53     }
54     return false;
55   }
56   public void release() {
57     try {
58       // TODO: verify that channel.close should be called after release() for rigourous locking. 
59       if (lock!=null && lock.isValid())
60         lock.release();
61       if (rafile!=null && rafile.getChannel().isOpen())
62         rafile.getChannel().close();
63     } catch (IOException e) {
64       // TODO Auto-generated catch block
65       e.printStackTrace(System.err);
66     }
67     lock=null;
68     rafile=null;
69   }
70   
71   /* Explicitly release lock (probably don't need to do this!)
72    * @see java.lang.Object#finalize()
73    */
74   protected void finalize() throws Throwable {
75     release();
76     super.finalize();
77   }
78   
79 }