static FileLock openLockedFileChannel()

in java/main/src/main/java/com/epam/deltix/utilities/ResourceLoaderUtils.java [145:192]


    static FileLock openLockedFileChannel(final Path filePath, final OpenOption... options) throws IOException {
        boolean truncate = false, shared = true;
        final Set<OpenOption> set = new HashSet<>(4);
        set.add(StandardOpenOption.READ);

        for (final OpenOption i : options) {
            if (i == StandardOpenOption.TRUNCATE_EXISTING) {
                shared = false;
                truncate = true;
                // DO NOT add this option to the list.
                continue;
            } else if (i == StandardOpenOption.APPEND || i == StandardOpenOption.WRITE || i == StandardOpenOption.CREATE_NEW) {
                shared = false;
            }

            set.add(i);
        }

        final FileChannel fileChannel = FileChannel.open(filePath, set, new FileAttribute[0]);
        FileLock fileLock = null;

        try {
            fileLock = fileChannel.tryLock(0, Long.MAX_VALUE, shared);
            if (null == fileLock) {
                log("tryLock(shared=%s): File is locked by another process! : %s", shared, filePath);
                throw new IOException(fmt("tryLock(shared=%s): File is locked by another process! : %s", shared, filePath));
            }

            log("Lock at: %s", filePath);

            if (truncate) {
                fileChannel.truncate(0);
                fileChannel.force(true);
            }

            fileChannel.position(0);
            return fileLock;
        } catch (final Throwable e) {
            if (null != fileLock)
                fileLock.close();

            fileChannel.close();
            if (e instanceof OverlappingFileLockException)
                throw new IOException(fmt("tryLock(shared=%s): File is locked by this JVM instance! : %s", shared, filePath));

            throw e;
        }
    }