X-Git-Url: http://source.jalview.org/gitweb/?a=blobdiff_plain;f=src%2Forg%2Fvamsas%2Fclient%2Fsimpleclient%2FLock.java;h=175728e2b618499629eacbc5fcfa1c10dd9ad563;hb=8c0230fceb94cba911790b1622b030d02eb0e7ac;hp=c4351d6102104c36e0ec67b2d0fbae8a61fe4a7f;hpb=31a237800ee9c6a324426645d395ae32db885a8e;p=vamsas.git diff --git a/src/org/vamsas/client/simpleclient/Lock.java b/src/org/vamsas/client/simpleclient/Lock.java index c4351d6..175728e 100644 --- a/src/org/vamsas/client/simpleclient/Lock.java +++ b/src/org/vamsas/client/simpleclient/Lock.java @@ -3,11 +3,12 @@ package org.vamsas.client.simpleclient; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; +import java.io.RandomAccessFile; import java.nio.channels.FileLock; /** * transient object representing a file lock - * + * This lock should hold for all processes interacting in a session. * * @author jimp * @@ -15,6 +16,7 @@ import java.nio.channels.FileLock; public class Lock { FileLock lock = null; + RandomAccessFile rafile=null; /** * creates a valid Lock (test with isLocked) * if a lock could be obtained for lockfile @@ -23,14 +25,17 @@ public class Lock { public Lock(java.io.File lockfile) { // try and get a lock. lock = null; - + try { if (!lockfile.exists()) if (!lockfile.createNewFile()) { return; } - - lock = new FileOutputStream(lockfile).getChannel().tryLock(); + + lock = (rafile=new RandomAccessFile(lockfile,"rw")).getChannel().tryLock(); + if (lock==null || !lock.isValid()) + // failed to get lock. Close the file channel + rafile.getChannel().close(); } catch (FileNotFoundException e) { System.err.println("Error! Couldn't create a lockfile at " + lockfile.getAbsolutePath()); @@ -41,20 +46,32 @@ public class Lock { e.printStackTrace(); } } - + boolean isLocked() { if (lock != null && lock.isValid()) { return true; } return false; } - + public void release() { + try { + if (lock!=null && lock.isValid()) + lock.release(); + if (rafile!=null && rafile.getChannel().isOpen()) + rafile.getChannel().close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(System.err); + } + lock=null; + rafile=null; + } + /* Explicitly release lock (probably don't need to do this!) * @see java.lang.Object#finalize() */ protected void finalize() throws Throwable { - if (lock!=null) - lock.release(); + release(); super.finalize(); }