"Java records" a pit of try-with-resources

Source: Internet
Author: User

"Java records" a pit of try-with-resources

Today, when dealing with a problem with Asynchronousfilechannel, the code is as follows:

public static void Main (string[] args) throws Exception {String FilePath = "/HOME/XE/GIT/OSC/JAVANOTE/LANG/DATA/TEST.J    Ava ";    Executorservice Executorservice = Executors.newsinglethreadexecutor (); set<openoption> openoptions = new Hashset<> (arrays.aslist (New standardopenoption[]{    Standardopenoption.read})); Try (Asynchronousfilechannel Asynchronousfilechannel = Asynchronousfilechannel.open (Paths.get (FilePath),        Openoptions, Executorservice)) {Bytebuffer buffer = bytebuffer.allocate (1024);            Asynchronousfilechannel.read (buffer, 0, buffer, new Completionhandler<integer, bytebuffer> () {@Override public void completed (Integer result, bytebuffer attachment) {System.out.println ("Completed,res                Ult = "+ result";            Executorservice.shutdown (); } @Override public void failed (Throwable exc, bytebuffer attachment) {System.out.pri                Ntln ("failed");Exc.printstacktrace ();            Executorservice.shutdown ();    }        }); } catch (Exception e) {}}

Always prompt:

java.nio.channels.AsynchronousCloseException

have been unable to find the cause of the problem, because I did not explicitly to close the Asynchronousfilechannel, later found that is the Try-with-resources feature to the closed, sad story.

Therefore, it is better to handle the closed operation of the advertisement in the asynchronous call or in a cautious process.

"Java records" a pit of try-with-resources

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.