Chapter 6. Java’s Approach to Memory and Concurrency

This chapter is an introduction to the handling of concurrency (multithreading) and memory in the Java platform. These topics are inherently intertwined, so it makes sense to treat them together. We will cover:

  • Introduction to Java’s memory management

  • The basic mark-and-sweep Garbage Collection (GC) algorithm

  • How the HotSpot JVM optimizes GC according to the lifetime of the object

  • Java’s concurrency primitives

  • Data visibility and mutability

Basic Concepts of Java Memory Management

In Java, the memory occupied by an object is automatically reclaimed when the object is no longer needed. This is done through a process known as garbage collection (or automatic memory management). Garbage collection is a technique that has been around for years in languages such as Lisp. It takes some getting used to for programmers accustomed to languages such as C and C++, in which you must call the free() function or the delete operator to reclaim memory.

Note

The fact that you don’t need to remember to destroy every object you create is one of the features that makes Java a pleasant language to work with. It is also one of the features that makes programs written in Java less prone to bugs than those written in languages that don’t support automatic garbage collection.

Different VM implementations handle garbage collection in different ways, and the specifications do not impose very stringent restrictions on how GC must be implemented. ...

Get Java in a Nutshell, 7th Edition 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.