public static void main(String args[]) throws IOException { if (args.length != 1) { System.err.println("Usage: java LockingExample <input file>"); System.exit(0); } FileLock sharedLock = null; FileLock exclusiveLock = null; try { RandomAccessFile raf = new RandomAccessFile(args[0], "rw"); // get the channel for the file FileChannel channel = raf.getChannel(); System.out.println("trying to acquire lock ..."); // this locks the first half of the file - exclusive exclusiveLock = channel.lock(0, raf.length() / 2, SHARED); System.out.println("lock acquired ..."); /** Now modify the data . . . */ try { // sleep for 10 seconds Thread.sleep(10000); } catch (InterruptedException ie) { } // release the lock exclusiveLock.release(); System.out.println("lock released ..."); // this locks the second half of the file - shared sharedLock = channel.lock(raf.length() / 2 + 1, raf.length(), SHARED); /** Now read the data . . . */ // release the lock sharedLock.release(); } catch (java.io.IOException ioe) { System.err.println(ioe); } finally { if (exclusiveLock != null) exclusiveLock.release(); if (sharedLock != null) sharedLock.release(); } }
public void run() { try { // Exclusive lock with no overlap: FileLock fl = fc.lock(start, end, false); System.out.println("Locked: " + start + " to " + end); // Perform modification: while (buff.position() < buff.limit() - 1) buff.put((byte) (buff.get() + 1)); fl.release(); System.out.println("Released: " + start + " to " + end); } catch (IOException e) { throw new RuntimeException(e); } }