should Class.getResourceAsStream be closed?












26















I was wondering if this is required since when i use this method, the file is being read from the classpath. Does "not closing" it lead to a memory leak.



How can i test for such memory leaks?










share|improve this question



























    26















    I was wondering if this is required since when i use this method, the file is being read from the classpath. Does "not closing" it lead to a memory leak.



    How can i test for such memory leaks?










    share|improve this question

























      26












      26








      26


      1






      I was wondering if this is required since when i use this method, the file is being read from the classpath. Does "not closing" it lead to a memory leak.



      How can i test for such memory leaks?










      share|improve this question














      I was wondering if this is required since when i use this method, the file is being read from the classpath. Does "not closing" it lead to a memory leak.



      How can i test for such memory leaks?







      java






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Oct 25 '13 at 19:36









      BobLoblawBobLoblaw

      6801921




      6801921
























          3 Answers
          3






          active

          oldest

          votes


















          21














          You are assuming that Class.getResourceAsStream() will always return a stream that points to a file inside your class' JAR file. This is incorrect. Your classpath may also contains folders, in which case Class.getResourceAsStream() will return a FileInputStream. Some other class loaders might also return other type of resources, such as remote files (in the case of a URLClassLoader).



          Even in the case of a JAR file, it is possible that the implementation maintain, by whatever mean, a persistant view inside the JAR file to the compressed bytes of the file you are accessing. Maybe it is holding upon a memory mapped ByteBuffer...



          Why take the chance? You should always close streams (and any other Closeable, actually), no matter how they were given to you.



          As for detecting leaks, the best strategy is to obtain a memory dump at the time the VM is shut down, then analyze it with some tool. Two popular tools are jhat and Eclipse mat.






          share|improve this answer

































            5














            As a rule of thumb you should close all streams (and ay other types that provide close functionality). It can lead ro resource leaks (memory is one type of resource).



            Although there is automatic garbage collection that reclaims memory eventually when an object is no longer referred to, it might still hold native resources that might not be released. Also, if some other long-lived object (e.g. the classloader) keeps a hold on the resource, it will not be claimed by the garbage collector.



            If your program is short lived, or f you only open a small number of resources, you might not run into problems, but resource leaks are hard to detect in long-running applications.






            share|improve this answer































              4














              The type returned is an inputstream so, regardless the concrete implementation (which could change from version to version), you have a close() method that imho should be called.



              No matter if that method is actually doing something useful with the current version.






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f19598088%2fshould-class-getresourceasstream-be-closed%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                21














                You are assuming that Class.getResourceAsStream() will always return a stream that points to a file inside your class' JAR file. This is incorrect. Your classpath may also contains folders, in which case Class.getResourceAsStream() will return a FileInputStream. Some other class loaders might also return other type of resources, such as remote files (in the case of a URLClassLoader).



                Even in the case of a JAR file, it is possible that the implementation maintain, by whatever mean, a persistant view inside the JAR file to the compressed bytes of the file you are accessing. Maybe it is holding upon a memory mapped ByteBuffer...



                Why take the chance? You should always close streams (and any other Closeable, actually), no matter how they were given to you.



                As for detecting leaks, the best strategy is to obtain a memory dump at the time the VM is shut down, then analyze it with some tool. Two popular tools are jhat and Eclipse mat.






                share|improve this answer






























                  21














                  You are assuming that Class.getResourceAsStream() will always return a stream that points to a file inside your class' JAR file. This is incorrect. Your classpath may also contains folders, in which case Class.getResourceAsStream() will return a FileInputStream. Some other class loaders might also return other type of resources, such as remote files (in the case of a URLClassLoader).



                  Even in the case of a JAR file, it is possible that the implementation maintain, by whatever mean, a persistant view inside the JAR file to the compressed bytes of the file you are accessing. Maybe it is holding upon a memory mapped ByteBuffer...



                  Why take the chance? You should always close streams (and any other Closeable, actually), no matter how they were given to you.



                  As for detecting leaks, the best strategy is to obtain a memory dump at the time the VM is shut down, then analyze it with some tool. Two popular tools are jhat and Eclipse mat.






                  share|improve this answer




























                    21












                    21








                    21







                    You are assuming that Class.getResourceAsStream() will always return a stream that points to a file inside your class' JAR file. This is incorrect. Your classpath may also contains folders, in which case Class.getResourceAsStream() will return a FileInputStream. Some other class loaders might also return other type of resources, such as remote files (in the case of a URLClassLoader).



                    Even in the case of a JAR file, it is possible that the implementation maintain, by whatever mean, a persistant view inside the JAR file to the compressed bytes of the file you are accessing. Maybe it is holding upon a memory mapped ByteBuffer...



                    Why take the chance? You should always close streams (and any other Closeable, actually), no matter how they were given to you.



                    As for detecting leaks, the best strategy is to obtain a memory dump at the time the VM is shut down, then analyze it with some tool. Two popular tools are jhat and Eclipse mat.






                    share|improve this answer















                    You are assuming that Class.getResourceAsStream() will always return a stream that points to a file inside your class' JAR file. This is incorrect. Your classpath may also contains folders, in which case Class.getResourceAsStream() will return a FileInputStream. Some other class loaders might also return other type of resources, such as remote files (in the case of a URLClassLoader).



                    Even in the case of a JAR file, it is possible that the implementation maintain, by whatever mean, a persistant view inside the JAR file to the compressed bytes of the file you are accessing. Maybe it is holding upon a memory mapped ByteBuffer...



                    Why take the chance? You should always close streams (and any other Closeable, actually), no matter how they were given to you.



                    As for detecting leaks, the best strategy is to obtain a memory dump at the time the VM is shut down, then analyze it with some tool. Two popular tools are jhat and Eclipse mat.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 21 '18 at 17:44









                    The Alchemist

                    3,0541319




                    3,0541319










                    answered Oct 25 '13 at 19:41









                    jwatkinsjwatkins

                    1,757619




                    1,757619

























                        5














                        As a rule of thumb you should close all streams (and ay other types that provide close functionality). It can lead ro resource leaks (memory is one type of resource).



                        Although there is automatic garbage collection that reclaims memory eventually when an object is no longer referred to, it might still hold native resources that might not be released. Also, if some other long-lived object (e.g. the classloader) keeps a hold on the resource, it will not be claimed by the garbage collector.



                        If your program is short lived, or f you only open a small number of resources, you might not run into problems, but resource leaks are hard to detect in long-running applications.






                        share|improve this answer




























                          5














                          As a rule of thumb you should close all streams (and ay other types that provide close functionality). It can lead ro resource leaks (memory is one type of resource).



                          Although there is automatic garbage collection that reclaims memory eventually when an object is no longer referred to, it might still hold native resources that might not be released. Also, if some other long-lived object (e.g. the classloader) keeps a hold on the resource, it will not be claimed by the garbage collector.



                          If your program is short lived, or f you only open a small number of resources, you might not run into problems, but resource leaks are hard to detect in long-running applications.






                          share|improve this answer


























                            5












                            5








                            5







                            As a rule of thumb you should close all streams (and ay other types that provide close functionality). It can lead ro resource leaks (memory is one type of resource).



                            Although there is automatic garbage collection that reclaims memory eventually when an object is no longer referred to, it might still hold native resources that might not be released. Also, if some other long-lived object (e.g. the classloader) keeps a hold on the resource, it will not be claimed by the garbage collector.



                            If your program is short lived, or f you only open a small number of resources, you might not run into problems, but resource leaks are hard to detect in long-running applications.






                            share|improve this answer













                            As a rule of thumb you should close all streams (and ay other types that provide close functionality). It can lead ro resource leaks (memory is one type of resource).



                            Although there is automatic garbage collection that reclaims memory eventually when an object is no longer referred to, it might still hold native resources that might not be released. Also, if some other long-lived object (e.g. the classloader) keeps a hold on the resource, it will not be claimed by the garbage collector.



                            If your program is short lived, or f you only open a small number of resources, you might not run into problems, but resource leaks are hard to detect in long-running applications.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Oct 25 '13 at 19:42









                            AttilaAttila

                            22.5k13245




                            22.5k13245























                                4














                                The type returned is an inputstream so, regardless the concrete implementation (which could change from version to version), you have a close() method that imho should be called.



                                No matter if that method is actually doing something useful with the current version.






                                share|improve this answer




























                                  4














                                  The type returned is an inputstream so, regardless the concrete implementation (which could change from version to version), you have a close() method that imho should be called.



                                  No matter if that method is actually doing something useful with the current version.






                                  share|improve this answer


























                                    4












                                    4








                                    4







                                    The type returned is an inputstream so, regardless the concrete implementation (which could change from version to version), you have a close() method that imho should be called.



                                    No matter if that method is actually doing something useful with the current version.






                                    share|improve this answer













                                    The type returned is an inputstream so, regardless the concrete implementation (which could change from version to version), you have a close() method that imho should be called.



                                    No matter if that method is actually doing something useful with the current version.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Oct 25 '13 at 19:40









                                    AndreaAndrea

                                    1,89421929




                                    1,89421929






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f19598088%2fshould-class-getresourceasstream-be-closed%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        MongoDB - Not Authorized To Execute Command

                                        How to fix TextFormField cause rebuild widget in Flutter

                                        in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith