public static boolean lock(File filename){
  boolean fileLockSucceeded=false;
  File lockFile=new File(filename + ".filelock");
  try {
    while (!fileLockSucceeded) {
      if (!lockFile.exists()) {
        final String PID=getPid();
        BufferedWriter out=new BufferedWriter(new FileWriter(lockFile));
        out.write(PID);
        out.close();
        fileLockSucceeded=true;
      }
 else {
        try {
          Thread.sleep(500);
        }
 catch (        InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
catch (  InterruptedException e) {
    e.printStackTrace();
  }
  return fileLockSucceeded;
}

public static boolean lock ( File filename ) { boolean fileLockSucceeded = false ; File lockFile = new File ( filename + ".filelock" ) ; try { while ( ! fileLockSucceeded ) { if ( ! lockFile . exists ( ) ) { final String PID = getPid ( ) ; BufferedWriter out = new BufferedWriter ( new FileWriter ( lockFile ) ) ; out . write ( PID ) ; out . close ( ) ; fileLockSucceeded = true ; } else { try { Thread . sleep ( 500 ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } return fileLockSucceeded ; }
lock a given file
