1. Write clear code using more life-cycle short, small, immutable-oriented objects.
We are accustomed to reusing a variable for laziness or simple frugality. But....
Java garbage collectors like the short lifecycle of objects, if the object in the Cenozoic, in the garbage collection before the death of the garbage collector will have nothing to do.
Modern JVMs need only 10 local CPU instructions to build a new object, not less than C + +. (garbage collection is slightly slower without compression algorithms, and more frequent new objects result in more frequent GC).
Large objects are less efficient to allocate, and are more likely to cause fragmentation to the garbage collectors of uncompressed algorithms.
Object reuse increases the complexity of the code and reduces readability.
So there's a headline appeal, like Don't be afraid to assign small objects to intermediate results. But the change in programming habits is not a matter of overnight.
2. Setting the finished object to null doesn't really work.
It looks cool. "Good habits" that set the object to null are actually useless, and JIT compiler automatically analyzes the life cycle of the local variable.
There is only one exception, that is, string[1024] foo's naked array, you need to actively foo[100]=null release 100th element, so it is best to use ArrayList these standard libraries.
3. Avoid an explicit GC--SYSTEM.GC ().
We all know System.GC () is bad, full-gc waste a lot, GC timing is not necessarily right, and so on, even have-XX:+DISABLEEXPLICITGC JVM parameters to prohibit it.
Haha, but I still do not use System.GC (), not afraid. Are you really not afraid?
First use FindBugs to check the use of all the third party class library bar ...
At least RMI will be honest. Execute System.GC () to implement the distributed GC algorithm. But I don't use RMI either. What about EJB, EJB is built on RMI ....
If unavoidable, increase the large GC interval with-dsun.rmi.dgc.client.gcinterval=3600000-dsun.rmi.dgc.server.gcinterval=3600000 (in subtle units) (the original default value is 1 minutes) ),-xx:+explicitgcinvokesconcurrent lets System.GC () also perform the CMS concurrently.
4. Continue Choufso's Finalize ()
We all know that the Finalize () is not good, the allocation cost is expensive, the cost of release is more expensive (it takes more than one loop, and they die slowly, and the objects associated with them die slowly), and are not sure whether they can be invoked (the JVM will not be garbage collected when it starts to shut down), and it is not sure when it is invoked ( GC time is uncertain, and even if System.GC () is merely a reminder rather than a forced GC, and is unsure in what order to invoke, Finalize is not a C + + destructor, nor is it like a C + + destructor.
We all know, so I've never used it. are explicitly maintaining those external resources, such as releasing them in finally{}.