Thursday, June 23, 2005

File sharing btw a Java and a non-Java application

Prior to JDK 1.4, it was not easy to share a file between multiple processes (Java or non Java). IT involved the use of native code. But in JDK 1.4 NIO (non blocking IO) was introduced with the concept of channels and file-locks.

The FileLock class, which is part of the java.nio.channels package, represents a file lock. You can use a file lock to restrict access to a file from multiple processes. In addition, you have the option of restricting access to an entire file or just a small region of it. A file lock is either shared or exclusive. A shared lock supports read access from multiple processes, while an exclusive lock is typically used for writing. Because a lock is at the file level, you should not use it to restrict access to a file from multiple threads in a single process. If you use a file lock in multiple threads, none of the threads would be restricted from accessing the file. Only external processes are restricted.