Skip to content

Instantly share code, notes, and snippets.

@nschlimm
Created April 4, 2012 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nschlimm/2301874 to your computer and use it in GitHub Desktop.
Save nschlimm/2301874 to your computer and use it in GitHub Desktop.
close method
/**
* Method that closes this file channel gracefully without loosing any data.
*/
@Override
public void close() throws IOException {
AsynchronousFileChannel writeableChannel = innerChannel;
System.out.println("Starting graceful shutdown ...");
closeLock.lock();
try {
state = PREPARE;
innerChannel = AsynchronousFileChannel.open(Paths.get(uri),
new HashSet<StandardOpenOption>(Arrays.asList(StandardOpenOption.READ)), pool);
System.out.println("Channel blocked for write access ...");
if (!pool.getQueue().isEmpty()) {
System.out.println("Waiting for signal that queue is empty ...");
isEmpty.await();
System.out.println("Received signal that queue is empty ... closing");
} else {
System.out.println("Don't have to wait, queue is empty ...");
}
} catch (InterruptedException e) {
Thread.interrupted();
throw new RuntimeException("Interrupted on awaiting Empty-Signal!", e);
} catch (Exception e) {
throw new RuntimeException("Unexpected error" + e);
} finally {
closeLock.unlock();
writeableChannel.force(false);
writeableChannel.close(); // close the writable channel
innerChannel.close(); // close the read-only channel
System.out.println("File closed ...");
pool.shutdown(); // allow clean up tasks from previous close() operation to finish safely
try {
pool.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
Thread.interrupted();
throw new RuntimeException("Could not terminate thread pool!", e);
}
System.out.println("Pool closed ...");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment