All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.kolibrifx.plovercrest.server.internal.engine.DataDirLock Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2010-2017, KolibriFX AS. Licensed under the Apache License, version 2.0.
 */

package com.kolibrifx.plovercrest.server.internal.engine;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import org.apache.log4j.Logger;
import com.kolibrifx.common.Disposable;
import com.kolibrifx.plovercrest.client.PlovercrestException;
import com.kolibrifx.plovercrest.client.TableLockedException;

public class DataDirLock implements Disposable {
    private static final Logger log = Logger.getLogger(DataDirLock.class);
    private static final String LOCKFILE = ".lockfile";

    private final RandomAccessFile lockFile;
    private final FileLock lock;

    public DataDirLock(final String dataDir) {
        this.lockFile = acquireLockFile(dataDir);
        try {
            this.lock = lockFile.getChannel().tryLock();
            if (this.lock == null) {
                throw new PlovercrestException("Failed to aquire lock for "
                        + new File(dataDir, LOCKFILE).getAbsolutePath()
                        + ". Another Plovercrest instance may be using the same directory.");
            }
        } catch (final OverlappingFileLockException e) {
            log.info("Caught OverlappingFileLockException");
            throw new TableLockedException(LOCKFILE);
        } catch (final IOException e) {
            log.error("Unexpected I/O error while acquiring lock: " + e.getMessage(), e);
            throw new PlovercrestException("Unexpected I/O error while acquiring lock: " + e.getMessage());
        }
    }

    private static RandomAccessFile acquireLockFile(final String dataPath) {
        final File file = new File(dataPath, LOCKFILE);
        try {
            return new RandomAccessFile(file, "rw");
        } catch (final FileNotFoundException e) {
            throw new PlovercrestException("Failed to create lock file " + file);
        }
    }

    @Override
    public void close() {
        try {
            lock.release();
            lockFile.close();
        } catch (final IOException e) {
            log.error("Failed to release lock", e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy