Pero Kulić
Pero Kulić

Reputation: 31

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?

Upvotes: 1

Views: 399

Answers (1)

user207421
user207421

Reputation: 311048

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.

Upvotes: 1

Related Questions