Chapter 11. References in Four Flavors

The java.lang.ref package is criminally underused in Java programming. Despite the enormous power of the classes within this package, you rarely see them in mainstream coding. Most likely, this is because using these classes properly requires a fairly deep understanding of the garbage-collection infrastructure in Java. However, once you understand garbage collection, you can create code that uses resources efficiently.

The Problem

One of the critical problems in the Online Only Bank data model from Chapter 8 is the high potential for memory leaks. In fact, the process of garbage collection is not enough to protect you from memory leaks. Garbage collection protects you from only one kind of memory leak, known as a lost pointer.

In languages such as C++, a memory leak resembles a lost pointer to an allocated block of memory. In this scenario, an object asks the runtime environment to allocate a block of memory. However, after this allocation, the pointer to the block is lost, perhaps through method return. There is a memory leak because there is a dead stack of allocated memory that the computer cannot use and to which the program can no longer get a pointer. In Java, this type of memory leak is not possible.

However, Java suffers from a different type of memory leak based on the garbage-collection paradigm itself. Since all objects in Java are references, they form an intricate web of associations; these associations can cause a memory leak. ...

Get Hardcore Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.