c4351d6102104c36e0ec67b2d0fbae8a61fe4a7f
[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.nio.channels.FileLock;
7
8 /**
9  * transient object representing a file lock
10  * 
11  * 
12  * @author jimp
13  * 
14  */
15
16 public class Lock {
17   FileLock lock = null;
18   /**
19    * creates a valid Lock (test with <method>isLocked</method>)
20    * if a lock could be obtained for <param>lockfile</param>
21    * @param lockfile
22    */
23   public Lock(java.io.File lockfile) {
24     // try and get a lock.
25     lock = null;
26
27     try {
28       if (!lockfile.exists())
29         if (!lockfile.createNewFile()) {
30           return;
31         }
32
33       lock = new FileOutputStream(lockfile).getChannel().tryLock();
34     } catch (FileNotFoundException e) {
35       System.err.println("Error! Couldn't create a lockfile at "
36           + lockfile.getAbsolutePath());
37       e.printStackTrace();
38     } catch (IOException e) {
39       System.err.println("Error! Problems with IO when creating a lock on "
40           + lockfile.getAbsolutePath());
41       e.printStackTrace();
42     }
43   }
44
45   boolean isLocked() {
46     if (lock != null && lock.isValid()) {
47       return true;
48     }
49     return false;
50   }
51
52   /* Explicitly release lock (probably don't need to do this!)
53    * @see java.lang.Object#finalize()
54    */
55   protected void finalize() throws Throwable {
56     if (lock!=null)
57       lock.release();
58     super.finalize();
59   }
60   
61 }