Do I have to implement garbage collection manually in Java?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?“implements Runnable” vs “extends Thread” in JavaImprove INSERT-per-second performance of SQLite?How do I convert a String to an int in Java?Creating a memory leak with JavaReplacing a 32-bit loop counter with 64-bit introduces crazy performance deviations

Calculating the number of days between 2 dates in Excel

Have I saved too much for retirement so far?

"lassen" in meaning "sich fassen"

How to color a zone in Tikz

Java - What do constructor type arguments mean when placed *before* the type?

Could solar power be utilized and substitute coal in the 19th century?

For airliners, what prevents wing strikes on landing in bad weather?

Meta programming: Declare a new struct on the fly

What was required to accept "troll"?

Is there a good way to store credentials outside of a password manager?

Can I Retrieve Email Addresses from BCC?

Is it okay / does it make sense for another player to join a running game of Munchkin?

In Star Trek IV, why did the Bounty go back to a time when whales were already rare?

How do ultrasonic sensors differentiate between transmitted and received signals?

Why are all the doors on Ferenginar (the Ferengi home world) far shorter than the average Ferengi?

How to check participants in at events?

The most efficient algorithm to find all possible integer pairs which sum to a given integer

Visiting the UK as unmarried couple

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

What to do when my ideas aren't chosen, when I strongly disagree with the chosen solution?

My boss asked me to take a one-day class, then signs it up as a day off

What is the opposite of 'gravitas'?

Does "Dominei" mean something?

Is exact Kanji stroke length important?



Do I have to implement garbage collection manually in Java?


Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?“implements Runnable” vs “extends Thread” in JavaImprove INSERT-per-second performance of SQLite?How do I convert a String to an int in Java?Creating a memory leak with JavaReplacing a 32-bit loop counter with 64-bit introduces crazy performance deviations













0















I already read some about garbage collection in Java, but I can't find the "best practice" to handle the garbage collection in code. Should I set every variable to null after use, or is it more efficient and performant to just use the default garbage collector? Or do I have to configure the garbage collector through the command line arguments in this case?



Thanks for your advice!










share|improve this question
























  • No, you have not

    – dehasi
    Mar 8 at 8:15











  • You are not supposed to handle any of that yourself. Java does all of that behind the scenes. You can add calls to the GC in your code specifically, but they'll just be "requests" to run the GC, they don't guarantee that it'll actually run. What you can do, is make sure that when variables become obsolete, you flag them as ready to be garbage collected

    – Stultuske
    Mar 8 at 8:16






  • 2





    Best practice is to let the JVM deal with it. Leave it alone. Mostly. Assigning null to variables is nearly always unnecessary. Running the GC is nearly always inadvisable; i.e. a bad idea. Tuning the GC is only advisable if you have clear evidence that the GC is behaving badly. (Ill-advised GC tuning may make GC performance worse than leaving it alone.)

    – Stephen C
    Mar 8 at 8:16












  • As with all optimizations: Forget it. Avoid stupid algorithms (e.g., bubble sort), use good data structures (there are tons of them in Java itself, more in Guava and other libraries), write clean code with short methods. Especially the GC is meant to work as is, the best practice for 99% cases is leaving it alone as more experienced people have tuned it already.

    – maaartinus
    Mar 9 at 0:13















0















I already read some about garbage collection in Java, but I can't find the "best practice" to handle the garbage collection in code. Should I set every variable to null after use, or is it more efficient and performant to just use the default garbage collector? Or do I have to configure the garbage collector through the command line arguments in this case?



Thanks for your advice!










share|improve this question
























  • No, you have not

    – dehasi
    Mar 8 at 8:15











  • You are not supposed to handle any of that yourself. Java does all of that behind the scenes. You can add calls to the GC in your code specifically, but they'll just be "requests" to run the GC, they don't guarantee that it'll actually run. What you can do, is make sure that when variables become obsolete, you flag them as ready to be garbage collected

    – Stultuske
    Mar 8 at 8:16






  • 2





    Best practice is to let the JVM deal with it. Leave it alone. Mostly. Assigning null to variables is nearly always unnecessary. Running the GC is nearly always inadvisable; i.e. a bad idea. Tuning the GC is only advisable if you have clear evidence that the GC is behaving badly. (Ill-advised GC tuning may make GC performance worse than leaving it alone.)

    – Stephen C
    Mar 8 at 8:16












  • As with all optimizations: Forget it. Avoid stupid algorithms (e.g., bubble sort), use good data structures (there are tons of them in Java itself, more in Guava and other libraries), write clean code with short methods. Especially the GC is meant to work as is, the best practice for 99% cases is leaving it alone as more experienced people have tuned it already.

    – maaartinus
    Mar 9 at 0:13













0












0








0








I already read some about garbage collection in Java, but I can't find the "best practice" to handle the garbage collection in code. Should I set every variable to null after use, or is it more efficient and performant to just use the default garbage collector? Or do I have to configure the garbage collector through the command line arguments in this case?



Thanks for your advice!










share|improve this question
















I already read some about garbage collection in Java, but I can't find the "best practice" to handle the garbage collection in code. Should I set every variable to null after use, or is it more efficient and performant to just use the default garbage collector? Or do I have to configure the garbage collector through the command line arguments in this case?



Thanks for your advice!







java performance garbage-collection jvm command-line-arguments






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 8:30







Marvin Klar

















asked Mar 8 at 8:13









Marvin KlarMarvin Klar

591321




591321












  • No, you have not

    – dehasi
    Mar 8 at 8:15











  • You are not supposed to handle any of that yourself. Java does all of that behind the scenes. You can add calls to the GC in your code specifically, but they'll just be "requests" to run the GC, they don't guarantee that it'll actually run. What you can do, is make sure that when variables become obsolete, you flag them as ready to be garbage collected

    – Stultuske
    Mar 8 at 8:16






  • 2





    Best practice is to let the JVM deal with it. Leave it alone. Mostly. Assigning null to variables is nearly always unnecessary. Running the GC is nearly always inadvisable; i.e. a bad idea. Tuning the GC is only advisable if you have clear evidence that the GC is behaving badly. (Ill-advised GC tuning may make GC performance worse than leaving it alone.)

    – Stephen C
    Mar 8 at 8:16












  • As with all optimizations: Forget it. Avoid stupid algorithms (e.g., bubble sort), use good data structures (there are tons of them in Java itself, more in Guava and other libraries), write clean code with short methods. Especially the GC is meant to work as is, the best practice for 99% cases is leaving it alone as more experienced people have tuned it already.

    – maaartinus
    Mar 9 at 0:13

















  • No, you have not

    – dehasi
    Mar 8 at 8:15











  • You are not supposed to handle any of that yourself. Java does all of that behind the scenes. You can add calls to the GC in your code specifically, but they'll just be "requests" to run the GC, they don't guarantee that it'll actually run. What you can do, is make sure that when variables become obsolete, you flag them as ready to be garbage collected

    – Stultuske
    Mar 8 at 8:16






  • 2





    Best practice is to let the JVM deal with it. Leave it alone. Mostly. Assigning null to variables is nearly always unnecessary. Running the GC is nearly always inadvisable; i.e. a bad idea. Tuning the GC is only advisable if you have clear evidence that the GC is behaving badly. (Ill-advised GC tuning may make GC performance worse than leaving it alone.)

    – Stephen C
    Mar 8 at 8:16












  • As with all optimizations: Forget it. Avoid stupid algorithms (e.g., bubble sort), use good data structures (there are tons of them in Java itself, more in Guava and other libraries), write clean code with short methods. Especially the GC is meant to work as is, the best practice for 99% cases is leaving it alone as more experienced people have tuned it already.

    – maaartinus
    Mar 9 at 0:13
















No, you have not

– dehasi
Mar 8 at 8:15





No, you have not

– dehasi
Mar 8 at 8:15













You are not supposed to handle any of that yourself. Java does all of that behind the scenes. You can add calls to the GC in your code specifically, but they'll just be "requests" to run the GC, they don't guarantee that it'll actually run. What you can do, is make sure that when variables become obsolete, you flag them as ready to be garbage collected

– Stultuske
Mar 8 at 8:16





You are not supposed to handle any of that yourself. Java does all of that behind the scenes. You can add calls to the GC in your code specifically, but they'll just be "requests" to run the GC, they don't guarantee that it'll actually run. What you can do, is make sure that when variables become obsolete, you flag them as ready to be garbage collected

– Stultuske
Mar 8 at 8:16




2




2





Best practice is to let the JVM deal with it. Leave it alone. Mostly. Assigning null to variables is nearly always unnecessary. Running the GC is nearly always inadvisable; i.e. a bad idea. Tuning the GC is only advisable if you have clear evidence that the GC is behaving badly. (Ill-advised GC tuning may make GC performance worse than leaving it alone.)

– Stephen C
Mar 8 at 8:16






Best practice is to let the JVM deal with it. Leave it alone. Mostly. Assigning null to variables is nearly always unnecessary. Running the GC is nearly always inadvisable; i.e. a bad idea. Tuning the GC is only advisable if you have clear evidence that the GC is behaving badly. (Ill-advised GC tuning may make GC performance worse than leaving it alone.)

– Stephen C
Mar 8 at 8:16














As with all optimizations: Forget it. Avoid stupid algorithms (e.g., bubble sort), use good data structures (there are tons of them in Java itself, more in Guava and other libraries), write clean code with short methods. Especially the GC is meant to work as is, the best practice for 99% cases is leaving it alone as more experienced people have tuned it already.

– maaartinus
Mar 9 at 0:13





As with all optimizations: Forget it. Avoid stupid algorithms (e.g., bubble sort), use good data structures (there are tons of them in Java itself, more in Guava and other libraries), write clean code with short methods. Especially the GC is meant to work as is, the best practice for 99% cases is leaving it alone as more experienced people have tuned it already.

– maaartinus
Mar 9 at 0:13












2 Answers
2






active

oldest

votes


















6














No, JVM does it for you. That's why it's a language with automatic memory management. If you want, because of performance issues, you can call:



Runtime r = Runtime.getRuntime();
r.gc();


but there is no guarantee, that garbage collector will remove non-referenced objects. It's rather a suggestion for JVM. Only if you know what you're doing. At your own risk.



What you can do is choose an implementation of garbage collector, that suits your needs. For example if you don't want to reclaim any memory, for testing purposes, you can choose epsilon by adding XX:+UseEpsilonGC flag.






share|improve this answer

























  • Bad advice. Running the gc() by hand is liable to make application performance worse ... 'cos an application doesn't usually have enough info to know when is the right time to run it.

    – Stephen C
    Mar 8 at 8:24











  • Agreed, added note, whank you for that point

    – Andronicus
    Mar 8 at 8:26



















2














The Garbage Collector mostly do the work himself. You dont need to anything. But you can even watch the Garbage Collector clearing the JVM Memory as seen in the picture



its not hard to tell where the garbage collector did his job... From https://raw.githubusercontent.com/dsyer/spring-boot-memory-blog/master/manual-gc-web.png




Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.




further information:Java Garbage Collection Basics






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%2f55059113%2fdo-i-have-to-implement-garbage-collection-manually-in-java%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    6














    No, JVM does it for you. That's why it's a language with automatic memory management. If you want, because of performance issues, you can call:



    Runtime r = Runtime.getRuntime();
    r.gc();


    but there is no guarantee, that garbage collector will remove non-referenced objects. It's rather a suggestion for JVM. Only if you know what you're doing. At your own risk.



    What you can do is choose an implementation of garbage collector, that suits your needs. For example if you don't want to reclaim any memory, for testing purposes, you can choose epsilon by adding XX:+UseEpsilonGC flag.






    share|improve this answer

























    • Bad advice. Running the gc() by hand is liable to make application performance worse ... 'cos an application doesn't usually have enough info to know when is the right time to run it.

      – Stephen C
      Mar 8 at 8:24











    • Agreed, added note, whank you for that point

      – Andronicus
      Mar 8 at 8:26
















    6














    No, JVM does it for you. That's why it's a language with automatic memory management. If you want, because of performance issues, you can call:



    Runtime r = Runtime.getRuntime();
    r.gc();


    but there is no guarantee, that garbage collector will remove non-referenced objects. It's rather a suggestion for JVM. Only if you know what you're doing. At your own risk.



    What you can do is choose an implementation of garbage collector, that suits your needs. For example if you don't want to reclaim any memory, for testing purposes, you can choose epsilon by adding XX:+UseEpsilonGC flag.






    share|improve this answer

























    • Bad advice. Running the gc() by hand is liable to make application performance worse ... 'cos an application doesn't usually have enough info to know when is the right time to run it.

      – Stephen C
      Mar 8 at 8:24











    • Agreed, added note, whank you for that point

      – Andronicus
      Mar 8 at 8:26














    6












    6








    6







    No, JVM does it for you. That's why it's a language with automatic memory management. If you want, because of performance issues, you can call:



    Runtime r = Runtime.getRuntime();
    r.gc();


    but there is no guarantee, that garbage collector will remove non-referenced objects. It's rather a suggestion for JVM. Only if you know what you're doing. At your own risk.



    What you can do is choose an implementation of garbage collector, that suits your needs. For example if you don't want to reclaim any memory, for testing purposes, you can choose epsilon by adding XX:+UseEpsilonGC flag.






    share|improve this answer















    No, JVM does it for you. That's why it's a language with automatic memory management. If you want, because of performance issues, you can call:



    Runtime r = Runtime.getRuntime();
    r.gc();


    but there is no guarantee, that garbage collector will remove non-referenced objects. It's rather a suggestion for JVM. Only if you know what you're doing. At your own risk.



    What you can do is choose an implementation of garbage collector, that suits your needs. For example if you don't want to reclaim any memory, for testing purposes, you can choose epsilon by adding XX:+UseEpsilonGC flag.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 8 at 8:26

























    answered Mar 8 at 8:17









    AndronicusAndronicus

    5,46421733




    5,46421733












    • Bad advice. Running the gc() by hand is liable to make application performance worse ... 'cos an application doesn't usually have enough info to know when is the right time to run it.

      – Stephen C
      Mar 8 at 8:24











    • Agreed, added note, whank you for that point

      – Andronicus
      Mar 8 at 8:26


















    • Bad advice. Running the gc() by hand is liable to make application performance worse ... 'cos an application doesn't usually have enough info to know when is the right time to run it.

      – Stephen C
      Mar 8 at 8:24











    • Agreed, added note, whank you for that point

      – Andronicus
      Mar 8 at 8:26

















    Bad advice. Running the gc() by hand is liable to make application performance worse ... 'cos an application doesn't usually have enough info to know when is the right time to run it.

    – Stephen C
    Mar 8 at 8:24





    Bad advice. Running the gc() by hand is liable to make application performance worse ... 'cos an application doesn't usually have enough info to know when is the right time to run it.

    – Stephen C
    Mar 8 at 8:24













    Agreed, added note, whank you for that point

    – Andronicus
    Mar 8 at 8:26






    Agreed, added note, whank you for that point

    – Andronicus
    Mar 8 at 8:26














    2














    The Garbage Collector mostly do the work himself. You dont need to anything. But you can even watch the Garbage Collector clearing the JVM Memory as seen in the picture



    its not hard to tell where the garbage collector did his job... From https://raw.githubusercontent.com/dsyer/spring-boot-memory-blog/master/manual-gc-web.png




    Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.




    further information:Java Garbage Collection Basics






    share|improve this answer



























      2














      The Garbage Collector mostly do the work himself. You dont need to anything. But you can even watch the Garbage Collector clearing the JVM Memory as seen in the picture



      its not hard to tell where the garbage collector did his job... From https://raw.githubusercontent.com/dsyer/spring-boot-memory-blog/master/manual-gc-web.png




      Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.




      further information:Java Garbage Collection Basics






      share|improve this answer

























        2












        2








        2







        The Garbage Collector mostly do the work himself. You dont need to anything. But you can even watch the Garbage Collector clearing the JVM Memory as seen in the picture



        its not hard to tell where the garbage collector did his job... From https://raw.githubusercontent.com/dsyer/spring-boot-memory-blog/master/manual-gc-web.png




        Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.




        further information:Java Garbage Collection Basics






        share|improve this answer













        The Garbage Collector mostly do the work himself. You dont need to anything. But you can even watch the Garbage Collector clearing the JVM Memory as seen in the picture



        its not hard to tell where the garbage collector did his job... From https://raw.githubusercontent.com/dsyer/spring-boot-memory-blog/master/manual-gc-web.png




        Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.




        further information:Java Garbage Collection Basics







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 8:26









        Jonas M.Jonas M.

        6010




        6010



























            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%2f55059113%2fdo-i-have-to-implement-garbage-collection-manually-in-java%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

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme