Skip to content

Commit 7c345eb

Browse files
authored
Merge pull request #307 from scijava/fix-filehandle-close
FileHandle: don't unnecessarily init a RandomAccessFile on close
2 parents 16c5f3f + 5f4b56a commit 7c345eb

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/main/java/org/scijava/io/handle/FileHandle.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ public class FileHandle extends AbstractDataHandle<FileLocation> {
5555
/** The mode of the {@link RandomAccessFile}. */
5656
private String mode = "rw";
5757

58+
/** True iff the {@link #close()} has already been called. */
59+
private boolean closed;
60+
5861
// -- FileHandle methods --
5962

6063
/** Gets the random access file object backing this FileHandle. */
@@ -289,8 +292,9 @@ public void writeUTF(final String str) throws IOException {
289292
// -- Closeable methods --
290293

291294
@Override
292-
public void close() throws IOException {
293-
raf().close();
295+
public synchronized void close() throws IOException {
296+
if (raf != null) raf().close();
297+
closed = true;
294298
}
295299

296300
// -- Typed methods --
@@ -308,6 +312,7 @@ private RandomAccessFile raf() throws IOException {
308312
}
309313

310314
private synchronized void initRAF() throws IOException {
315+
if (closed) throw new IOException("Handle already closed");
311316
if (raf != null) return;
312317
raf = new RandomAccessFile(get().getFile(), getMode());
313318
}

src/test/java/org/scijava/io/handle/FileHandleTest.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,23 @@ public void testExists() throws IOException {
8989
// Clean up.
9090
assertTrue(nonExistentFile.delete());
9191
}
92+
93+
@Test
94+
public void testNotCreatedByClose() throws IOException {
95+
final Context ctx = new Context();
96+
final DataHandleService dhs = ctx.service(DataHandleService.class);
97+
98+
final File nonExistentFile = //
99+
File.createTempFile("FileHandleTest", "nonexistent-file");
100+
assertTrue(nonExistentFile.delete());
101+
assertFalse(nonExistentFile.exists());
102+
103+
final FileLocation loc = new FileLocation(nonExistentFile);
104+
final DataHandle<?> handle = dhs.create(loc);
105+
assertTrue(handle instanceof FileHandle);
106+
assertFalse(handle.exists());
107+
108+
handle.close();
109+
assertFalse(nonExistentFile.exists());
110+
}
92111
}

0 commit comments

Comments
 (0)