Search in sources :

Example 71 with FileLock

use of java.nio.channels.FileLock in project com.revolsys.open by revolsys.

the class ScaledIntegerGriddedDigitalElevationModelFile method setElevations.

public void setElevations(final int gridX, final int gridY, final double[] elevations) {
    try {
        final FileChannel fileChannel = getFileChannel();
        if (fileChannel != null) {
            ByteBuffer buffer = this.rowBuffer;
            final int gridWidth2 = getGridWidth();
            if (buffer == null) {
                buffer = ByteBuffer.allocateDirect(4 * gridWidth2);
                this.rowBuffer = buffer;
            }
            final double scale = this.scaleZ;
            for (final double elevation : elevations) {
                final int elevationInt;
                if (Double.isFinite(elevation)) {
                    elevationInt = (int) Math.round(elevation * scale);
                } else {
                    elevationInt = Integer.MIN_VALUE;
                }
                buffer.putInt(elevationInt);
            }
            final int offset = this.headerSize + (gridY * gridWidth2 + gridX) * ELEVATION_BYTE_COUNT;
            if (this.useLocks) {
                try (FileLock lock = fileChannel.lock(offset, elevations.length * ELEVATION_BYTE_COUNT, false)) {
                    Buffers.writeAll(fileChannel, buffer, offset);
                }
            } else {
                Buffers.writeAll(fileChannel, buffer, offset);
            }
        }
    } catch (final IOException e) {
        throw Exceptions.wrap("Unable to read: " + this.path, e);
    }
}
Also used : FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 72 with FileLock

use of java.nio.channels.FileLock in project energy3d by concord-consortium.

the class OneInstance method register.

/**
 * Registers this instance of the application. Returns true if the application is allowed to run or false when the application must exit immediately.
 *
 * @param mainClass
 *            The main class of the application. Must not be null. This is used for determining the application ID and as the user node key for the preferences.
 * @param args
 *            The command line arguments. They are passed to an already running instance if found. Must not be null.
 * @return True if instance is allowed to start, false if not.
 */
public boolean register(final Class<?> mainClass, final String[] args) {
    if (mainClass == null)
        throw new IllegalArgumentException("mainClass must be set");
    if (args == null)
        throw new IllegalArgumentException("args must be set");
    // Determine application ID from class name.
    final String appId = mainClass.getName();
    try {
        // Acquire a lock
        final File lockFile = getLockFile(appId);
        final FileLock lock = lock(lockFile);
        try {
            // Get the port which is currently recorded as active.
            final Integer port = getActivePort(mainClass);
            // If port is found then we have to validate it
            if (port != null) {
                // Try to connect to the first instance.
                final Socket socket = openClientSocket(appId, port);
                // (non-first instance)
                if (socket != null) {
                    try {
                        // server
                        return runClient(socket, args);
                    } finally {
                        socket.close();
                    }
                }
            }
            // Run the server
            runServer(mainClass);
            // Mark the lock file to be deleted when this instance exits.
            lockFile.deleteOnExit();
            // Allow this first instance to run.
            return true;
        } finally {
            release(lock);
        }
    } catch (final IOException e) {
        // When something went wrong log the error as a warning and then
        // let instance start.
        e.printStackTrace();
        return true;
    }
}
Also used : FileLock(java.nio.channels.FileLock) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) Socket(java.net.Socket)

Example 73 with FileLock

use of java.nio.channels.FileLock in project tutorials by eugenp.

the class JavaWriteToFileUnitTest method whenTryToLockFile_thenItShouldBeLocked.

@Test
public void whenTryToLockFile_thenItShouldBeLocked() throws IOException {
    final RandomAccessFile stream = new RandomAccessFile(fileName4, "rw");
    final FileChannel channel = stream.getChannel();
    FileLock lock = null;
    try {
        lock = channel.tryLock();
    } catch (final OverlappingFileLockException e) {
        stream.close();
        channel.close();
    }
    stream.writeChars("test lock");
    lock.release();
    stream.close();
    channel.close();
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) Test(org.junit.Test)

Example 74 with FileLock

use of java.nio.channels.FileLock in project derby by apache.

the class RollingFileStream method openFiles.

/**
 * Opens the output files files based on the configured pattern, limit, count,
 * and append mode.
 * @throws IOException
 */
private void openFiles() throws IOException {
    if (count < 1) {
        throw new IllegalArgumentException("file count = " + count);
    }
    if (limit < 0) {
        limit = 0;
    }
    // Create a lock file.  This grants us exclusive access
    // to our set of output files, as long as we are alive.
    int unique = -1;
    for (; ; ) {
        unique++;
        if (unique > MAX_LOCKS) {
            throw new IOException("Couldn't get lock for " + pattern);
        }
        // Generate a lock file name from the "unique" int.
        lockFileName = generate(pattern, 0, unique).toString() + ".lck";
        // if we ourself already have the file locked.
        synchronized (locks) {
            if (locks.get(lockFileName) != null) {
                // object.  Try again.
                continue;
            }
            FileChannel fc;
            try {
                lockStream = openFile(lockFileName, false);
                fc = lockStream.getChannel();
            } catch (IOException ix) {
                // Try the next file.
                continue;
            }
            try {
                FileLock fl = fc.tryLock();
                if (fl == null) {
                    // We failed to get the lock.  Try next file.
                    continue;
                }
            // We got the lock OK.
            } catch (IOException ix) {
            // We got an IOException while trying to get the lock.
            // This normally indicates that locking is not supported
            // on the target directory.  We have to proceed without
            // getting a lock.   Drop through.
            }
            // We got the lock.  Remember it.
            locks.put(lockFileName, lockFileName);
            break;
        }
    }
    files = new File[count];
    for (int i = 0; i < count; i++) {
        files[i] = generate(pattern, i, unique);
    }
    // Create the initial log file.
    if (append) {
        open(files[0], true);
    } else {
        rotate();
    }
}
Also used : FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException)

Example 75 with FileLock

use of java.nio.channels.FileLock in project incubator-pulsar by apache.

the class PortManager method nextFreePort.

/**
 * Return a TCP port that is currently unused.
 *
 * Keeps track of assigned ports and avoid race condition between different processes
 */
public static synchronized int nextFreePort() {
    Path path = Paths.get(lockFilename);
    try {
        FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        FileLock lock = fileChannel.lock();
        try {
            FileReader reader = new FileReader(lockFilename);
            CharBuffer buffer = CharBuffer.allocate(16);
            int len = reader.read(buffer);
            buffer.flip();
            int lastUsedPort = basePort;
            if (len > 0) {
                String lastUsedPortStr = buffer.toString();
                lastUsedPort = Integer.parseInt(lastUsedPortStr);
            }
            int freePort = probeFreePort(lastUsedPort + 1);
            FileWriter writer = new FileWriter(lockFilename);
            writer.write(Integer.toString(freePort));
            reader.close();
            writer.close();
            return freePort;
        } finally {
            lock.release();
            fileChannel.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : Path(java.nio.file.Path) FileChannel(java.nio.channels.FileChannel) FileWriter(java.io.FileWriter) FileLock(java.nio.channels.FileLock) CharBuffer(java.nio.CharBuffer) FileReader(java.io.FileReader) IOException(java.io.IOException)

Aggregations

FileLock (java.nio.channels.FileLock)246 IOException (java.io.IOException)127 RandomAccessFile (java.io.RandomAccessFile)99 FileChannel (java.nio.channels.FileChannel)83 File (java.io.File)77 OverlappingFileLockException (java.nio.channels.OverlappingFileLockException)37 FileOutputStream (java.io.FileOutputStream)29 Test (org.junit.Test)19 Path (java.nio.file.Path)16 FileInputStream (java.io.FileInputStream)13 FileNotFoundException (java.io.FileNotFoundException)12 ByteBuffer (java.nio.ByteBuffer)10 InputStream (java.io.InputStream)5 Properties (java.util.Properties)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 NonWritableChannelException (java.nio.channels.NonWritableChannelException)4 NoSuchFileException (java.nio.file.NoSuchFileException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Map (java.util.Map)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3