Search code examples
javafileasynchronousfilechannel

java.nio.channels.AsynchronousClose Exception on Java 8


I just moved my code from java 7 windows to java 1.8 Linux and i am getting this stack trace on same code base

java.nio.channels.AsynchronousCloseException at sun.nio.ch.SimpleAsynchronousFileChannelImpl$3.run(SimpleAsynchronousFileChannelImpl.java:380) [rt.jar:1.8.0_92] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_92] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_92] at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_92]

My codes is as below

  Charset cs = Charset.forName("UTF-8");
        byte[] inputBytes = jsonString.getBytes(cs);
        fileChannel.write(ByteBuffer.wrap(inputBytes), 0, ByteBuffer.wrap(inputBytes),new CompletionHandler<Integer, ByteBuffer>() {

            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                log.info("Async Saving site content completed for sitename");
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                exc.printStackTrace();
                log.error("Async File Write Failed",exc);
                log.fatal(exc);
            }
        });

Wonder what is happening. Any help is appreciated.


Solution

  • As per the comment i took a second look and the above code was enclosed in a try catch with a finally statement that has a FileStream "close" method call. Culprit is that finally statement closes the channel when the other thread is writing into the channel.

    I removed the finally block and moved the close file stream code into completion handler and it works now.

    Note : How it worked in windows still eludes me. The code is still deployed in Windows servers and right before i write this , i retested and it works with the finally block in there :). Anyways wont spend any more time on this.

    Marking it resolved. Thanks a lot for all the pointers.