]> nmode's Git Repositories - signal-cli/commitdiff
Cleanup fileChannel if file locking fails
authorAsamK <asamk@gmx.de>
Wed, 18 May 2022 13:27:02 +0000 (15:27 +0200)
committerAsamK <asamk@gmx.de>
Wed, 18 May 2022 14:04:35 +0000 (16:04 +0200)
lib/src/main/java/org/asamk/signal/manager/storage/SignalAccount.java

index 33b9e80cc305525a58880d9ce4d5dbd7d3d3cfea..79f436701df5f990d115d716755d951f65647524 100644 (file)
@@ -884,17 +884,25 @@ public class SignalAccount implements Closeable {
 
     private static Pair<FileChannel, FileLock> openFileChannel(File fileName, boolean waitForLock) throws IOException {
         var fileChannel = new RandomAccessFile(fileName, "rw").getChannel();
-        var lock = fileChannel.tryLock();
-        if (lock == null) {
-            if (!waitForLock) {
-                logger.debug("Config file is in use by another instance.");
-                throw new IOException("Config file is in use by another instance.");
+        try {
+            var lock = fileChannel.tryLock();
+            if (lock == null) {
+                if (!waitForLock) {
+                    logger.debug("Config file is in use by another instance.");
+                    throw new IOException("Config file is in use by another instance.");
+                }
+                logger.info("Config file is in use by another instance, waiting…");
+                lock = fileChannel.lock();
+                logger.info("Config file lock acquired.");
+            }
+            final var result = new Pair<>(fileChannel, lock);
+            fileChannel = null;
+            return result;
+        } finally {
+            if (fileChannel != null) {
+                fileChannel.close();
             }
-            logger.info("Config file is in use by another instance, waiting…");
-            lock = fileChannel.lock();
-            logger.info("Config file lock acquired.");
         }
-        return new Pair<>(fileChannel, lock);
     }
 
     public void addPreKeys(ServiceIdType serviceIdType, List<PreKeyRecord> records) {