When to Garbage Collect

前端 未结 8 1194
逝去的感伤
逝去的感伤 2020-12-11 04:24

I have a piece of code that load a very big image in memory. So it seemed like a reasonable thing to call

System.gc();

before loading the

相关标签:
8条回答
  • 2020-12-11 04:37

    Did you get any performance improvements with the System.gc()? I don't think so, since you probably dont have a lot of objects that needs to be collected before you load the image.

    Usually modern garbage collectors know best when to run, so you shouldnt force a collection, unless you have a really really good reason to. (for example a benchmarking application as suggested by that plugin)

    btw: Calling System.gc() recommends the VM to perform a "full" or "large" collection, which means that all threads are stopped shortly. Otherwise it will probably only make "small" garbage collections, which don't stop all threads.

    Run your program with -verbose:gc to see how many bytes are collected.

    There is also lots of technical information on garbage collection here: http://java.sun.com/developer/technicalArticles/Programming/GCPortal/

    0 讨论(0)
  • 2020-12-11 04:41

    It's fine to call the garbage collector, you don't get any "problems" from it. However, I doubt it will significently boost performance, unless that call also deals with defragging the allocated data. I don't know that.

    What you should do in this case is profile the code. Run it several times, see what sort of results you get.

    0 讨论(0)
  • 2020-12-11 04:43

    Typically the GC is smarter than you, so it's better to let it run whenever the runtime decides. If the runtime needs memory, it'll run the GC itself

    0 讨论(0)
  • 2020-12-11 04:44

    Ensure that the large objects can be gc'ed as early as possible. I.e. set variables to null and/or let them fall out of scope. THis helps!

    0 讨论(0)
  • 2020-12-11 04:47

    You already got plenty of good advice, which I will try not to reiterate.

    If you actually get problems with the GC, like full stops of your application for a second, do the following: 1. check that there aren't any calls to System.gc(); 2. check out the various options for configuring the gc. There are tons of those around, and they are much more helpful, then forcing gc.

    0 讨论(0)
  • 2020-12-11 04:54

    If a memory allocation fails, a GC cycle is initiated and the allocation is tried again.

    0 讨论(0)
提交回复
热议问题