Search code examples
javaconcurrencyfilechannelfilelock

How to lock file for another threads


This is my method that compresses file into archive:

public void addFilesToArchive(File source, File destination) throws 
IOException, ArchiveException {

    try (FileOutputStream archiveStream = new FileOutputStream(destination);
          ArchiveOutputStream archive = new ArchiveStreamFactory()
                  .createArchiveOutputStream(getType(), archiveStream)) {

        updateSourceFolder(source);
        generateFileAndFolderList(source);

        for (String entryName : fileList) {
            ArchiveEntry entry = getEntry(entryName);
            archive.putArchiveEntry(entry);
            archive.closeArchiveEntry();
        }
    }
}

fileList conatains all file hierarchy (folder and files)

I want to prevent compressing from different threads into one destination at the same time.

Try to use:

FileChannel channel = archiveStream.getChannel();
channel.lock();

but it doesn't seem to be helpful. How can i solve this problem?


Solution

  • You are trying to lock the file against other threads, not other processes, and this is exactly what file locks don't do. See the Javadoc. You need to use synchronization or semaphores.