Skip to content

Instantly share code, notes, and snippets.

@nschlimm
Created March 20, 2012 16:29
Show Gist options
  • Save nschlimm/2137930 to your computer and use it in GitHub Desktop.
Save nschlimm/2137930 to your computer and use it in GitHub Desktop.
Ordinary channel close
public class SimpleChannelClose_AsynchronousCloseException {
private static final String FILE_NAME = "E:/temp/afile.out";
private static AsynchronousFileChannel outputfile;
private static AtomicInteger fileindex = new AtomicInteger(0);
private static ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
public static void main(String[] args) throws InterruptedException, IOException, ExecutionException {
outputfile = AsynchronousFileChannel.open(
Paths.get(FILE_NAME),
new HashSet<StandardOpenOption>(Arrays.asList(StandardOpenOption.WRITE, StandardOpenOption.CREATE,
StandardOpenOption.DELETE_ON_CLOSE)), pool);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
futures.add(outputfile.write(ByteBuffer.wrap("Hello".getBytes()), fileindex.getAndIncrement() * 5));
}
outputfile.close();
pool.shutdown();
pool.awaitTermination(60, TimeUnit.SECONDS);
for (Future<Integer> future : futures) {
try {
future.get();
} catch (ExecutionException e) {
System.out.println("Task wasn't executed!");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment