Created
April 4, 2012 14:36
-
-
Save nschlimm/2301874 to your computer and use it in GitHub Desktop.
close method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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