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. * TODO: currently implemented for local filesystem style locking - need a fallback mechanism for systems without file locks. * @author jimp * */ public class Lock { FileLock lock = null; RandomAccessFile rafile=null; /** * creates a valid Lock (test with isLocked) * if a lock could be obtained for lockfile * @param lockfile */ public Lock(java.io.File lockfile) { // try and get a lock. lock = null; try { if (!lockfile.exists()) if (!lockfile.createNewFile()) { return; } 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()); e.printStackTrace(); } catch (IOException e) { System.err.println("Error! Problems with IO when creating a lock on " + lockfile.getAbsolutePath()); e.printStackTrace(); } } boolean isLocked() { if (lock != null && lock.isValid()) { return true; } return false; } public void release() { try { // TODO: verify that channel.close should be called after release() for rigourous locking. 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 { release(); super.finalize(); } }