2

I have a java standalone application which will process files from a directory.This java application runs in AIX box triggered by a cron job which runs every 1 min once.My aim is if one invocation of the java application accesses a particular file in that directory,that file should get locked for access by the second or other invocations until the first java invocation processes it and releases the lock.

Is there any way in java to lock the file programmatically ?This code should work in AIX particularly

user1929905
  • 389
  • 3
  • 9
  • 25

3 Answers3

0

The standard way of doing this is to create a FileChannel out of your file and call .lock() on it. This method will create a FileLock object which you have to .release().

If you cannot acquire the lock, you will get an OverlappingFileLockException.

Alternatively, you can "lock" the file using a sentinel directory: select a path for it, create the directory, do whatever you need to do, and delete the directory on exit. If you cannot create the directory, it means another process has the upper hand.

Whatever method you choose, be sure to release the lock or delete the directory in a finally block!

fge
  • 119,121
  • 33
  • 254
  • 329
0

You can lock files using NIO, something along the lines of

try
{
    RandomAccessFile file = new RandomAccessFile( "yourfile.txt" , "rw" );
    FileChannel fc = file.getChannel();
    FileLock fileLock = fc.tryLock();
    if ( fileLock != null )
    {
        // Do stuff on the file
    }
}
catch ( OverlappingFileLockException e )
{
    // File was locked
}

should work.

Cheers,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
0

Instead of starting a process via cron every minute, it might be better to wait (sleep) in the handling process for periods of a minute.

If your aim is to process the files you access, you can also achieve the same with renaming the file when it is ready to be processed. In Unix os-ses renames are atomic.

For instance you write data to a file spool-${timestamp} and rename it to data-${timestamp} when it is ready to be processed. The handling process waits for data-${timestamp} files which it can process and delete as soon as they appear without the need for extra locking mechanisms.

rsp
  • 23,135
  • 6
  • 55
  • 69