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);
}
}
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;
}
}
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();
}
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();
}
}
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);
}
}
Aggregations