What are good Java coding practices to help Java GC? [duplicate]

荒凉一梦 提交于 2020-02-04 04:07:09

问题


Possible Duplicate:
How can I avoid garbage collection delays in Java games? (Best Practices)

Java's GC pause is a killer. Often the time, the application doesn't have the memory leak. At some point, it may pause for ~1 second for every 1G memory allocation.

What are good Java coding practices to help Java GC?

One example, since null object becomes eligible for garbage collection, so it is a good idea to explicitly set an object to null e.g. object = null.


回答1:


The single best thing that you can do to minimize GC pauses is to properly size your heap.

If you know that your program never uses more than 1Gb of live objects, then it's pointless to pass -Xms4096m. That will actually increase your GC pauses, because the JVM will leave garbage around until it absolutely has to clear it.

Similarly, if you know that you have very few long-lived objects, you can usually benefit by increasing the size of the young generation relative to the tenured generation (for Sun JVMs).

The only thing that you can really do, coding-wise, is to move large objects off-heap. But that's unlikely to be useful for most applications.




回答2:


In general to help GC you should avoid of unreasonable memory usage. Simple advices could be:

1) Do not produce new objects, where it is not needed. For example do not use constructions like String test = new String("blabla");. If it possible, reuse old objects (it belongs to immutable objects mainly).

2) Do not declare fields in classes, where they are used only inside methods; i.e. make them local variables.

3) Avoid of using object wrappers under primitive types. I.e. use int instead of Integer, boolean instead of Boolean, if you really do not need to store in them null values. Also for example, where it is possible, for memory economy, do not use ArrayList, use simple Java arrays of primitive types (not Integer[], but int[]).




回答3:


Objects that are allocated and not immediately released get moved into the tenured heap space. Tenured memory is the most expensive to collect. Avoid churning through long lived objects should help with GC pauses.



来源:https://stackoverflow.com/questions/14403774/what-are-good-java-coding-practices-to-help-java-gc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!