Item - 7 Eliminate Obsolete Object References

Berat Yesbek
2 min readAug 24, 2023

--

This writing will discuss item 7 in Effective JAVA, recommended by Joshua Bloch.

I just remembered not to mention autoboxing and unboxing previous writing.

Autoboxing

Autoboxing is the automatic conversion of primitive types to wrapper classes.

List<Integer> array = new ArrayList<Integer>();
int number = 60;
array.add(number); // Autoboxing converts the int to Integer

Unboxing

Unboxing is the reverse process. It is the automatic conversion of a wrapper class to a primitive type.

int number = array.get(0); // Unboxing converts the Integer to int

Autoboxing and unboxing can cost performance overhead.

Static

Static keywords must be used judiciously on the objects. Because Garbage Collection cannot collect static objects until Garbage Collected or the JVM shuts down.

Static objects are not associated with an instance of a class but with the class itself.

The best practice to dispose of memory leaks is to set the references to null.

Whenever a class manages its memory, the programmer should be alert for memory leaks. [1]

public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
// this code received from EFFECTIVE JAVA Item - 7

Caches

Caches also might cause memory leaks. When you put the references to the caches, it is easy to forget that it’s there. There are several solutions to solve this problem. Use WeakHashMap but do not forget to determine external references to the key, not the value. For more information (Item 7 in Effective JAVA) [1]

Conclusion

Use static keywords judiciously and eliminate absolute objects.

REFERENCES

Bloch, Joshua. Effective Java Programming Third Edition. [1]

--

--

Berat Yesbek
Berat Yesbek

No responses yet