Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failed to acquire lock for collection file ClosedChannelException #62

Open
Srdjan-V opened this issue Jul 6, 2024 · 0 comments
Open

Comments

@Srdjan-V
Copy link

Srdjan-V commented Jul 6, 2024

If you try to upsert a large collection that contains new and updated items the operation will fail.

Failed to acquire lock for collection file X.json
java.nio.channels.ClosedChannelException: null
	at java.base/sun.nio.ch.FileChannelImpl.ensureOpen(FileChannelImpl.java:160) ~[?:?]
	at java.base/sun.nio.ch.FileChannelImpl.lock(FileChannelImpl.java:1463) ~[?:?]
	at java.base/java.nio.channels.FileChannel.lock(FileChannel.java:1240) ~[?:?]
	at io.jsondb.io.JsonWriter.acquireLock(JsonWriter.java:101) ~[jsondb-core-1.0.115-j11.jar:?]
	at io.jsondb.io.JsonWriter.updateInJsonFile(JsonWriter.java:601) ~[jsondb-core-1.0.115-j11.jar:?]
	at io.jsondb.JsonDBTemplate.upsert(JsonDBTemplate.java:1257) ~[jsondb-core-1.0.115-j11.jar:?]
	at io.jsondb.JsonDBTemplate.upsert(JsonDBTemplate.java:1194) ~[jsondb-core-1.0.115-j11.jar:?]

After the items get appended, the file channel will get closed, causing the update to fail since its unable to obtain the file lock.

if (collectionToInsert.size() > 0) {
boolean insertResult = jw.appendToJsonFile(collection.values(), collectionToInsert.values());
if(insertResult) {
collection.putAll(collectionToInsert);
}
}
if (collectionToUpdate.size() > 0) {
boolean updateResult = jw.updateInJsonFile(collection, collectionToUpdate);
if (updateResult) {
collection.putAll(collectionToUpdate);
}

private void releaseLock(FileLock lock) {
try {
if(lock != null && lock.isValid()) {
lock.release();
}
} catch (IOException e) {
logger.error("Failed to release lock for collection file {}", collectionFile.getName(), e);
}
try {
channel.close();
} catch (IOException e) {
logger.error("Failed to close FileChannel for collection file {}", collectionFile.getName(), e);
}
try {
raf.close();
} catch (IOException e) {
logger.error("Failed to close RandomAccessFile for collection file {}", collectionFile.getName(), e);
}
}

private FileLock acquireLock() throws IOException {
try {
FileLock fileLock= channel.lock();
return fileLock;
} catch (IOException e) {
try {
channel.close();
raf.close();
} catch (IOException e1) {
logger.error("Failed while closing RandomAccessFile for collection file {}", collectionFile.getName());
}
throw e;
}
}

Srdjan-V added a commit to Srdjan-V/jsondb-core that referenced this issue Jul 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant