Search code examples
javaserializationconcurrencynio

Can two different program perform synchronization on the same file for I/O?


We have a situation where in two different main() programs access the same file for read/write operation.

One of the program tries to serialize a HashMap into the file whereas the other program tries to read the same HashMap.

The aim is to prevent the read operation while the write operation is ongoing.

I am able to get a lock for the file using java.nio.channels.FileChannel.lock(). But now I am unable to write to the file using ObjectOutputStream, since the lock is acquired by the FileChannel.

The main method for the write looks like as given below:

public static void main(String args[]) {
try {
HashMap<String, Double> h = new HashMap<>();
File f = new File("C:\\Sayan\\test.txt");
FileChannel channel = new RandomAccessFile(f, "rw").getChannel();
FileLock lock = channel.lock();
System.out.println("Created File object");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
System.out.println("Created output stream");
oos.writeObject(h);
lock.release();
 } catch (Exception e) {
  e.printStackTrace();
}

}

The read operation is also similar it just reads the data from the file modified by above code.

Constraints: We cannot create any other class or threading for attaining synchronization.

One more doubt: Can threads created by two different main programs communicate with each other?


Solution

  • Get the channel you're locking with from the FileOutputStream instead of from a separate RandomAccessFile.