一个麻烦的遗留问题:Java 中的内存泄漏

  • Article Source: Featured in the new DZone Guide to Java: Development and Evolution. Get the free copy at https://dzone.com/guides/java-development-and-evolution.
  • Memory Leak Discussion:

    • Problem: Memory leaks are a silent killer in Java, especially in Android where memory is limited. They grow over time and can lead to performance issues and crashes.
    • Causes: Examples include not closing open streams, using static fields to hold references, and using a HashSet with incorrect hashCode() or equals(). In Android, the object Context is often passed around and can cause leaks.
    • Avoidance: Use WeakReferences and other reference types like SoftReferences. For example, in an Android AsyncTask, make the inner class static and use a WeakReference to the outer Activity to avoid memory leaks. Also, avoid using non-static inner classes in Activities, use Activity Context instead of Application Context, and never keep long-term references to any Context.
  • Reference Types in Java:

    • Normal: The main type of reference. An object is collected when no longer used.
    • Soft: Not strong enough to keep an object in memory during a garbage collection event. The garbage collector decides when to free the object memory.
    • Weak: Weaker than SoftReferences.
    • Phantom: The weakest reference; the object is eligible for finalization. This kind of reference is rarely used.
阅读 4
0 条评论