Java Memory Management, with its built-in garbage collection, is one of the language’s finest achievements. It allows developers to create new objects without worrying explicitly about memory allocation and deallocation, because the garbage collector automatically reclaims memory for reuse. This enables faster development with less boilerplate code, while eliminating memory leaks and other memory-related problems. At least in theory.

Ironically, Java garbage collection seems to work too well, creating and removing too many objects. Most memory-management issues are solved, but often at the cost of creating serious performance problems. Making garbage collection adaptable to all kinds of situations has led to a complex and hard-to-optimize system. In order to wrap your head around garbage collection, you need first to understand how memory management works in a Java Virtual Machine (JVM).

How Garbage Collection Really Works

Many people think garbage collection collects and discards dead objects. In reality, Java garbage collection is doing the opposite! Live objects are tracked and everything else designated garbage. As you’ll see, this fundamental misunderstanding can lead to many performance problems.

Let's start with the heap, which is the area of memory used for dynamic allocation. In most configurations the operating system allocates the heap in advance to be managed by the JVM while the program is running. This has a couple of important ramifications:

  • Object creation is faster because global synchronization with the operating system is not needed for every single object. An allocation simply claims some portion of a memory array and moves the offset pointer forward (see Figure 2.1). The next allocation starts at this offset and claims the next portion of the array.
  • When an object is no longer used, the garbage collector reclaims the underlying memory and reuses it for future object allocation. This means there is no explicit deletion and no memory is given back to the operating system.
Figure 2.1: New objects are simply allocated at the end of the used heap.

All objects are allocated on the heap area managed by the JVM. Every item that the developer uses is treated this way, including class objects, static variables, and even the code itself. As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory. As simple as this sounds, it raises a question: what is the first reference in the tree?

Garbage-Collection Roots — The Source of All Object Trees

Every object tree must have one or more root objects. As long as the application can reach those roots, the whole tree is reachable. But when are those root objects considered reachable? Special objects called garbage-collection roots (GC roots; see Figure 2.2) are always reachable and so is any object that has a garbage-collection root at its own root.

There are four kinds of GC roots in Java:

  1. Local variables are kept alive by the stack of a thread. This is not a real object virtual reference and thus is not visible. For all intents and purposes, local variables are GC roots.
  2. Active Java threads are always considered live objects and are therefore GC roots. This is especially important for thread local variables.
  3. Static variables are referenced by their classes. This fact makes them de facto GC roots. Classes themselves can be garbage-collected, which would remove all referenced static variables. This is of special importance when we use application servers, OSGi containers or class loaders in general. We will discuss the related problems in the Problem Patterns section.
  4. JNI References are Java objects that the native code has created as part of a JNI call. Objects thus created are treated specially because the JVM does not know if it is being referenced by the native code or not. Such objects represent a very special form of GC root, which we will examine in more detail in the Problem Patterns section below.
Figure 2.2: GC roots are objects that are themselves referenced by the JVM and thus keep every other object from being garbage-collected.

Therefore, a simple Java application has the following GC roots:

  • Local variables in the main method
  • The main thread
  • Static variables of the main class

Marking and Sweeping Away Garbage

To determine which objects are no longer in use, the JVM intermittently runs what is very aptly called a mark-and-sweep algorithm. As you might intuit, it’s a straightforward, two-step process:

  1. The algorithm traverses all object references, starting with the GC roots, and marks every object found as alive.
  2. All of the heap memory that is not occupied by marked objects is reclaimed. It is simply marked as free, essentially swept free of unused objects.

Garbage collection is intended to remove the cause for classic memory leaks: unreachable-but-not-deleted objects in memory. However, this works only for memory leaks in the original sense. It’s possible to have unused objects that are still reachable by an application because the developer simply forgot to dereference them. Such objects cannot be garbage-collected. Even worse, such a logical memory leak cannot be detected by any software (see Figure 2.3). Even the best analysis software can only highlight suspicious objects. We will examine memory leak analysis in the Analyzing the Performance Impact of Memory Utilization and Garbage Collection section, below.

Figure 2.3: When objects are no longer referenced directly or indirectly by a GC root, they will be removed. There are no classic memory leaks. Analysis cannot really identify memory leaks; it can only point out suspicious objects.

Java Memory Management(1)的更多相关文章

  1. 转)Understanding Java Memory Management

    Understanding Java Memory Management - IBM Java Native Interface (JNI) Objects and Code Java Native ...

  2. Java Memory Management

    How Memory works in Java The role of the stack - Each time you call a function, Java pushed the loca ...

  3. Java Memory Management Skill List

    Java内存管理小技巧: 尽量使用直接量 当需要使用字符串,还有Byte,Short,Integer,Long,Float,Double,Boolean,Character包装类的实例时,程序不应该采 ...

  4. Java (JVM) Memory Model – Memory Management in Java

    原文地址:http://www.journaldev.com/2856/java-jvm-memory-model-memory-management-in-java Understanding JV ...

  5. Understanding Java Memory Model-理解java内存模型(JVM)

    from https://medium.com/platform-engineer/understanding-java-memory-model-1d0863f6d973 Understanding ...

  6. jmap命令(Java Memory Map)(转)

    JDK内置工具使用 一.javah命令(C Header and Stub File Generator) 二.jps命令(Java Virtual Machine Process Status To ...

  7. Android内存管理(1)WRANGLING DALVIK: MEMORY MANAGEMENT IN ANDROID PART 1

    from : http://www.raizlabs.com/dev/2014/03/wrangling-dalvik-memory-management-in-android-part-1-of-2 ...

  8. The Introduction of Java Memory Leaks

    One of the most significant advantages of Java is its memory management. You simply create objects a ...

  9. Understanding Memory Management(2)

    Understanding Memory Management Memory management is the process of allocating new objects and remov ...

随机推荐

  1. 详解Windows 7系统中IE8/IE9/IE10三个版本的关系(转)

    今年(2013)年初,微软开放了姗姗来迟的 IE10 for Windows 7 版本下载.至此,Windows 7 平台上可以运行三个 IE 浏览器版本.虽然 Windows 与 IE 经历了诸多版 ...

  2. C#语法需要注意的地方

    笔试中遇到的一些C#语法方面的问题,由于平时很少用到,笔试的时候模棱两可,现在做一个笔记. using System; using System.Collections.Generic; using ...

  3. jquery <li>标签 隔若干行 加空白或者加虚线

    $(function () { $('ul li').addClass(function (i) { return i % 6 == 5 ? "ab" : "" ...

  4. Markdown语法备忘

    标题 标题 标题是每篇文章都需要也是最常用的格式,在 Markdown 中,如果一段文字被定义为标题,只要在这段文字前加 # 号即可. # 一级标题 ## 二级标题 ### 三级标题 以此类推,总共六 ...

  5. 前端资源多个产品整站一键打包&包版本管理(二)——如何在bower的配置文件加上注释

    问题: 当一个工程里面有好几个项目,每个项目引用同一个包,但是不同的名字,例如在bower中 fancybox 跟 jquery.fancybox 是一样的,我们只需要下载其中的一个版本,而打包工作不 ...

  6. jcom2在win7 X86上操作Excel

    浅谈Java中利用JCOM实现仿Excel编程   在JAVA中使用JCOM和JXL注意要点: (1)在你的lib下要有jdom-1.0.jar,jxl-2.5.5.jar,jcom-2.2.4.ja ...

  7. 基于Mahout的电影推荐系统

    基于Mahout的电影推荐系统 1.Mahout 简介 Apache Mahout 是 Apache Software Foundation(ASF) 旗下的一个开源项目,提供一些可扩展的机器学习领域 ...

  8. 关于github在mac 10.10上无法提交代码的解决办法---备用

    接下来是正文:本文主要说明在mac 10.10版本下github无法提交代码的问题 首先如果你是一个用终端提交代码的,你可以不用看这篇文章了,这篇文章主要是用于解决github客户端提交代码的问题,此 ...

  9. iOS实现地图半翻页效果--老代码备用参考

    // Curl the image up or down CATransition *animation = [CATransition animation]; [animation setDurat ...

  10. .net 添加不同项目框架引用出现的问题

    问题描述: winform项目添加web项目时出现问题,winform项目添加web项目类时,老是报找不到这个类的命名空间 最后才知道两个项目所建的框架不一样,一个是.net framework 4, ...