private void doWithLock ( FileChannel channel , Consumer < FileLock > consumer ) { FileLock lock = null ; try { while ( lock == null ) { try { lock = channel . tryLock ( ) ; } catch ( OverlappingFileLockException e ) { Thread . sleep ( 500 ) ; } } consumer . accept ( lock ) ; } catch ( IOException | InterruptedException e ) { error ( "Unable to write" , e ) ; } finally { try { if ( lock != null ) { lock . release ( ) ; } } catch ( IOException e ) { error ( "Unable to close lock" , e ) ; } } }
executes with a lock