Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Java IoT, IBM Cloud, Containers Expo Blog

Java IoT: Article

Anatomy of a Java Finalizer

Experimenting on finalizer implementations in various Java Virtual Machines

A couple of patterns that could cause Java heap exhaustion were identified from years of research at IBM. One interesting scenario was observed when Java applications generated an excessive amount of finalizable objects whose classes had non-trivial Java finalizers.

What Is a Java Finalizer?
A Java finalizer performs finalization tasks for an object. It's the opposite of a Java constructor, which creates and initializes an instance of a Java class. A Java finalizer can be used to perform postmortem cleanup tasks on an instance of a class or to release system resources such as file descriptors or network socket connections when an object is no longer needed and those resources have to be released for other objects. You don't need any argument or any return value for a finalizer. Unfortunately the current Java language specification does not define any finalizers for a Java class or interface when a class or interface is unloaded. Let's take a closer look at finalize() method of java.lang.Object that provides an instance method, finalize() for finalization:

protected void finalize() throws Throwable

When a Java object is no longer needed, the space occupied by the object is supposed to be recycled automatically by the Java garbage collector. This is one of the significant differences in Java and is not found in most structural programming languages like C. If an instance of a class implements the finalize() method, its space cannot be recycled by the garbage collector in a timely fashion. Worst case, it may not be recycled at all.

Any instances of classes that implement the finalize() method are often called finalizable objects. They will not be immediately reclaimed by the Java garbage collector when they are no longer referenced. Instead, the Java garbage collector appends the objects to a special queue for the finalization process. Usually it's performed by a special thread called a "Reference Handler" on some Java Virtual Machines. During this finalization process, the "Finalizer" thread will execute each finalize() method of the objects. Only after successful completion of the finalize() method will an object be handed over for Java garbage collection to get its space reclaimed by "future" garbage collection. I did not say "current," which means at least two garbage collection cycles are required to reclaim the finalizable object. Sounds like it has some overhead? You got it. We need several shots to get the space recycled.

Finalizer threads are not given maximum priorities on systems. If a "Finalizer" thread cannot keep up with the rate at which higher priority threads cause finalizable objects to be queued, the finalizer queue will keep growing and cause the Java heap to fill up. Eventually the Java heap will get exhausted and a java.lang.OutOfMemoryError will be thrown.

A Java Virtual Machine will never invoke the finalize() method more than once for any object. If there's any exception thrown by the finalize() method, the finalization of the object is halted.

You are free to do virtually anything in the finalize() method of your class. When you do that, please do not expect the memory space occupied by each and every object to be reclaimed by the Java garbage collector when the object is no longer referenced or no longer needed. Why? It is not guaranteed that the finalize() method will complete the execution in timely manner. Worst case, it may not be even invoked even when there are no more references to the object. That means it's not guaranteed that any objects that have a finalize() method are garbage collected. That's a potential hazard from a memory management perspective and, needless to say, there is considerable overhead for queuing, dequeuing, running the finalize() method, and rescanning the object in the next garbage collection cycle.

If you want to run cleanup tasks on objects, consider finalizers as a last resort and implement your own cleanup method, which will be more predictable. It's very risky to rely on finalizers for postmortem cleanup tasks, especially if your finalizable objects have references to native resources.

Hands-on Experience with Java Finalizer
We can easily simulate this scenario with a couple of test applications and take a look at dumps and traces to see what's happening inside of the Java heap and threads for hands-on experience.

Let's build a couple of Java classes to recreate typical scenarios.

In ObjectWYieldFinalizer, we can implement the method finalize() with Thread.yield() so that finalize() cannot complete its execution (see Listing 1) (Listings 1-7 can be downloaded here.)

The Thread.yield() method prevents the currently executing thread from running and allows other threads to execute. If the Finalizer thread calls this finalize() method, it will pause its execution.

In ObjectWExceptionFinalizer, the finalizer() method immediately throws a java.lang.IndexOutOfBoundsException. If the Finalizer thread calls this finalize() method, the object finalization won't be completed because of the exception and there's no second chance to run the finalize() method (see Listing 2).

In ObjectWEmptyFinalizer, we don't implement any code in the finalize() method (see Listing 3). ObjectWOFinalizer doesn't have any finalize() method (see Listing 4).

Let's run each of the classes to see what happens. Sun's Java Virtual Machine (JVM) can be used with the following options for the class TestObjectWYieldFinalizer.

/sun1.6.0_10/bin/java -Xmx50m -verbosegc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGC -XX:+HeapDumpOnOutOfMemoryError TestObjectWYieldFinalizer > verbosegc.txt

It looks very complicated. Why do we need those command-line options? Well, without those options, we only get a little information about Java garbage collection activities like this:

[Full GC 50815K->45644K(50816K), 0.2276940 secs]
[Full GC 48780K->46415K(50816K), 0.2233279 secs]
[Full GC 49551K->49551K(50816K), 0.2396315 secs]
[Full GC 50815K->50815K(50816K), 0.1886312 secs]
[Full GC 50815K->49219K(50816K), 0.1964926 secs]
[Full GC 50815K->50815K(50816K), 0.1865343 secs]
[Full GC 50815K->50815K(50816K), 0.1836961 secs]

We only get a type of garbage collection (Full GC), total Java heap usage before garbage collection (50,815K), total Java heap usage after garbage collection (45,644K), a high watermark of total Java heap (50,816K), and time spent in the garbage collection (0.2276940 secs).

High watermark is the size of the current Java heap. The Java heap can expand its size up to a maximum size or contract to manage Java heap effectively.

The -XX:+PrintGCDetails option lets the JVM provide information on each generation in the Java heap.

We can see Java heap usage and the time (in seconds) spent in Java garbage collection of each new generation, tenured generation, and permanent generation with the -XX:+PrintGCDetails option in the following example:

[GC [DefNew: 3520K->3520K(3520K), 0.0001143 secs][Tenured: 43897K->47295K(47296K), 0.2110999 secs] 47417K->47415K(50816K), [Perm : 17K->17K(12288K)], 0.2115593 secs]
[Times: user=0.22 sys=0.00, real=0.22 secs]

In tenured generation, Java heap usage was 43,897KB before this Java garbage collection. Java heap usage reached 47,295KB after Java garbage collection; 47296K is the size of the high watermark of the tenured generation; 0.2110999 second was spent to collect the tenured generation. Unfortunately we do not see the maximum size of each generation with the -XX:+PrintGCDetails option alone.

With -XX:+PrintGCTimeStamps, we can get a timestamp for each garbage collection like this:

1.393: [GC 1002K->106K(5056K), 0.0001036 secs]

This garbage collection started 1.393 seconds after the JVM started.

The -XX:+PrintHeapAtGC option provides extensive information about each Java garbage collection (see Listing 5).

We can even see the address range of each generation. Unfortunately there's no timestamp for each garbage collection with -XX:+PrintHeapAtGC option alone.

The last option, -XX:-HeapDumpOnOutOfMemoryError allows the JVM to dump the Java heap to a file when an allocation from the Java heap cannot be satisfied or a java.lang.OutOfMemoryError is thrown. This option was introduced in Sun Java 1.4.2 update 12 and Sun Java 5.0 update 7.

If you want to experiment with IBM's Java Virtual Machine, all you need is a -verbosegc command-line option. You do not need any of these: -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGC, or -XX:+HeapDumpOnOutOfMemoryError.

Let's take a look at what happened to the class while we talked about Sun JVM's command-line option. We've got java.lang.OutOfMemoryError from TestObjectWYieldFinalizer:

Exception in the thread "main" java.lang.OutOfMemoryError: Java heap space
at java.lang.ref.Finalizer.register(Finalizer.java:72)
at java.lang.Object.<init>(Object.java:20)
at ObjectWYieldFinalizer.<init>(ObjectWYieldFinalizer.java:2)
at TestObjectWYieldFinalizer.main(TestObjectWYieldFinalizer.java:11)

"java.lang.OutOfMemoryError: Java heap space." That means we got Java heap space exhaustion. The JVM could not allocate any more Java heap while running the method java.lang.ref.Finalizer.register(), which is on line 72 of Finalizer.java. Finalizer.java? Of course, we did not write Finalizer.java. That's a part of the JVM. We can also check verbosegc.txt to which we redirected the garbage collection trace (see Listing 6).

About 3.711 seconds after the JVM started, we got java.lang.OutOfMemoryError. The Java heap dump is written to pid124.hprof.

Analysis of Java Garbage Collection Traces
We can use a tool to analyze this trace. The IBM Pattern Modeling and Analysis Tool for Java Garbage Collector (PMAT) is one of top five technologies at alphaWorks. I have implemented patented algorithms to predict future failures related to Java heap exhaustion in this tool. Please refer to United States Patent No. 7,475,214 if you are interested in the algorithms. Although we don't need these algorithms to investigate simple problem like this, you might be able to find situations where you could get some insight from fortune tellers. We can get a copy of the tool here.

PMAT parses verbose garbage collection (GC) trace, analyzes Java heap usage, and recommends possible solutions based on pattern modeling of Java heap usage.

The following features are included:

  • GC analysis
  • GC table view
  • Allocation failure summary
  • GC usage summary
  • GC duration summary
  • GC graph view
  • GC pattern analysis
  • Zoom in/out/selection/center of chart view

The tool can also parse Sun's Java garbage collector traces, including the following:

  • Serial collector
  • Throughput/parallel collector
  • Concurrent collector
  • Incremental/train collector

We can start version 3.2 of the tool with a jar file in the download package. (V3.2 was the latest version when this article was written.)

# /usr/java5/bin/java -Xmx200m -jar ga32.jar

The tool provides a headless mode but let's bring up the graphical user interface mode for easy demonstration. We can click on the "N" icon to open Sun's trace file. We can click on "I" for IBM's trace file as seen in Figure 1.

We can see in Figure 2 the analysis result and recommendation virtually instantly.

More Stories By Jinwoo Hwang

Jinwoo Hwang is a software engineer, inventor, author, and technical leader at IBM WebSphere Application Server Technical Support in Research Triangle Park, North Carolina. He joined IBM in 1995 and worked with IBM Global Learning Services, IBM Consulting Services, and software development teams prior to his current position at IBM. He is an IBM Certified Solution Developer and IBM Certified WebSphere Application Server System Administrator as well as a SUN Certified Programmer for the Java platform. He is the architect and creator of the following technologies:

Mr. Hwang is the author of the book C Programming for Novices (ISBN:9788985553643, Yonam Press, 1995) as well as the following webcasts and articles:

Mr. Hwang is the author of the following IBM technical articles:

  • VisualAge Performance Guide,1999
  • CORBA distributed object applet/servlet programming for IBM WebSphere Application Server and VisualAge for Java v2.0E ,1999
  • Java CORBA programming for VisualAge for Java ,1998
  • MVS/CICS application programming for VisualAge Generator ,1998
  • Oracle Native/ODBC application programming for VisualAge Generator ,1998
  • MVS/CICS application Web connection programming for VisualAge Generator ,1998
  • Java applet programming for VisualAge WebRunner ,1998
  • VisualAge for Java/WebRunner Server Works Java Servlet Programming Guide ,1998
  • RMI Java Applet programming for VisualAge for Java ,1998
  • Multimedia Database Java Applet Programming Guide ,1997
  • CICS ECI Java Applet programming guide for VisualAge Generator 3.0 ,1997
  • CICS ECI DB2 Application programming guide for VigualGen, 1997
  • VisualGen CICS ECI programming guide, 1997
  • VisualGen CICS DPL programming guide, 1997

Mr. Hwang holds the following patents in the U.S. / other countries:


Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
vishetty 07/30/09 07:28:00 AM EDT

Hi,
you seem to say that,
"If there's any exception thrown by the finalize() method, the finalization of the object is halted.", But the Java Language specification seems to say "If an uncaught exception is thrown during the finalization, the exception is ignored and finalization of that object terminates".
Is this is a IBM JVM specific behavior?

@ThingsExpo Stories
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things’). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing? IoT is not about the devices, it’s about the data consumed and generated. The devices are tools, mechanisms, conduits. In his session at Internet of Things at Cloud Expo | DXWor...