1 package org.vamsas.client.simpleclient;
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;
10 * transient object representing a file lock
11 * This lock should hold for all processes interacting in a session.
19 RandomAccessFile rafile=null;
21 * creates a valid Lock (test with <method>isLocked</method>)
22 * if a lock could be obtained for <param>lockfile</param>
25 public Lock(java.io.File lockfile) {
26 // try and get a lock.
30 if (!lockfile.exists())
31 if (!lockfile.createNewFile()) {
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());
43 } catch (IOException e) {
44 System.err.println("Error! Problems with IO when creating a lock on "
45 + lockfile.getAbsolutePath());
51 if (lock != null && lock.isValid()) {
56 public void release() {
58 // TODO: verify that channel.close should be called after release() for rigourous locking.
59 if (lock!=null && lock.isValid())
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);
71 /* Explicitly release lock (probably don't need to do this!)
72 * @see java.lang.Object#finalize()
74 protected void finalize() throws Throwable {