Skip to content

Instantly share code, notes, and snippets.

@nschlimm
Created April 4, 2012 14:36
Show Gist options
  • Select an option

  • Save nschlimm/2301874 to your computer and use it in GitHub Desktop.

Select an option

Save nschlimm/2301874 to your computer and use it in GitHub Desktop.

Revisions

  1. nschlimm created this gist Apr 4, 2012.
    41 changes: 41 additions & 0 deletions gistfile1.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    /**
    * 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 ...");
    }
    }