Java IoT Authors: Pat Romanski, Yeshim Deniz, Elizabeth White, Roger Strukhoff, Liz McMillan

Related Topics: Java IoT, Microservices Expo

Java IoT: Article

The Impact of Garbage Collection on Java Performance

Before tuning the garbage collector, we first need to know what we want to tune

In my last article I explained what a major Garbage Collection is. While a major Collection certainly has a negative impact on performance it is not the only thing that we need to watch out for. And in case of the CMS we might not always be able to distinguish between major and minor GC. So before we start tuning the garbage collector we first need to know what we want to tune for. From a high level there are two main tuning goals.

Execution Time vs. Throughput
The first thing we need to clarify if we want to minimize the time the application needs to respond to a request or if we want to maximize the throughput. As with every other optimization these are competing goals and we can only fully satisfy one of them. If we want to minimize response time we care about the impact a GC has on the response time first and on resource usage second. If we optimize for throughput we don't care about the impact on a single transaction. That gives us two main things to monitor and tune for: runtime suspension and Garbage Collection CPU usage. Regardless of which we tune for, we should always make sure that a GC run is as short as possible, but what determines the duration of GC run?

What Makes a GC slow?
Although it is called Garbage Collection the amount of collected garbage has only indirect impact on the speed of a run. What actually determines this is the number of living objects. To understand this let's take a quick look at how Garbage Collection works.

Every GC will traverse all living objects beginning at the GC roots and mark them as alive. Depending on the strategy it will then copy these objects to a new area (Copy GC), move them (compacting GC) or put the free areas into a free list. This means that the more objects stay alive the longer the GC takes.The same is true for the copy phase and the compacting phase. The more objects stay alive, the long it takes. The fastest possible run is when all objects are garbage collected!

With this in mind let's have a look at the impact of garbage collections.

Impact on Response Time
Whenever a GC is triggered all application threads are stopped. In my last post I explained that this is true for all GCs to some degree, even for so called minor GCs.  As a rule every GC except the CMS (and possibly the G1) will suspend the JVM for the complete duration of a run.

The easiest way to measure impact on the response time is to use your favorite tool to monitor for major and minor collections via JMX and correlate the duration with the response time of your application.

The problem with this is that we only look at aggregates, so the impact on a single transaction is unknown. In this picture it does seem like there is no impact due to the garbage collections. A better way of doing this is to use the JVM-TI interface to get notified about stop-the-world events. This way the response time correlation is 100% correct, whereas otherwise it would depend on the JMX polling frequency. In addition, measuring the impact that the CMS has on response time is harder as its runs do not stop the JVM for the whole time and since Update 23 the JMX Bean does not report the real major GC anymore. In this case we need to use either verbose:gc or a solution like dynaTrace that can accurately measure runtime suspensions via a native agent technology.

Here we see a constant but small impact on average, but the impact on specific purepaths is sometimes in the 10 percent range. Optimizing for minimal response time impact has two sides. First we need to get the sizing of the young generation just right. Optimal would be that no object survives its first garbage collection, because then the GC would be fastest and the suspension the shortest possible. As this optimum can not be achieved we need to make sure that no object gets promoted to old space and that an objects dies as young as possible. We can monitor that by looking at the survivor spaces.

This chart shows the survivor space utilization. It always stays well above 50% which means that a lot of objects survive each GC. If we were to look at the old generation it would most likely be growing, which is obviously not what we want. Getting the sizing right, also means using the smallest young generation possible. If it is too big, more objects will be alive and need to be checked, thus a GC will take longer.

If after the initial warmup phase no more objects get promoted to old space, we will not need to do any special tuning of the old generation. If only a few objects get promoted over time and we can take a momentary hit on response time once in a while we should choose a parallel collector in the old space, as it is very efficient and avoids some problems that the CMS has. If we cannot take the hit in response time, we need to choose the CMS.

The Concurrent Mark and Sweep Collector will attempt to have as little response time impact as possible by working mostly concurrently with the application. There are only two scenarios where it will fail. Either we allocate too many objects too fast, in which case it cannot keep up and will trigger an "old-style" major GC; or no object can be allocated due to fragmentation. In such a case a compaction or a full GC (serial old) must be triggered. Compaction cannot be done concurrent to the application and will suspend the application threads.

If we have to use a continuous heap and need to tune for response time we will always choose a concurrent strategy.

Every GC needs CPU. In the young generation this is directly related to the number of times and duration of the collections. In old space and a  continuous  heap things are different. While CMS is a good idea to achieve low pause time, it will consume more CPU, due to its higher complexity. If we want to optimize throughput without having any SLA on a single transaction we will always prefer a parallel GC to the concurrent one. There are two thinkable optimization strategies. Either enough memory so that no objects get promoted to old space and old generation collections never occur, or have the least amount of objects possible living all the time. It is important to note that the first option does not imply that increasing memory is a solution for GC related problems in general. If the old space keeps growing or fluctates a lot than increasing the heap does not help, it will actually make things worse. While GC runs will occur less often, they will be that much longer as more objects might need checking and moving. As GCs becomes more expensive with the number of objects living, we need to minimize that factor.

Allocation Speed
The last and properly least known impact of a GC strategy is the allocation speed. While a young generation allocation will always be fast, this is not true in the old generation or in a continuous heap. In these two cases continued allocation and garbage collection leads to memory fragmentation

To solve this problem the GC will do a compaction to defragment the area. But not all GCs do a compact all the time or they do it incrementally. The reason is simple, compaction would again be a stop-the-world event, which GC strategies try to avoid. The Concurrent Mark and Sweep of the Sun JVM does not compact at all. Because of that these GCs must maintain a so called free list to keep track of free memory areas. This in turn has an impact on allocation speed. Instead of just allocating an object at the end of the used memory, java has to go through this list and find a big enough free area for the newly allocated object.

This impact is the hardest to diagnose, as it cannot be measured directly. One indicator is a slowdown of the application without any other apparent reasons, only to be fast again after the next major GC. The only way to avoid this problem is to use a compaction GC, which will lead to more expensive GCs. The only other thing we can do is to avoid unnecessary allocations while keeping the amount of memory usage low.

Finally allocate as much as you like, but forget as soon as possible, before the next GC run if possible. Still don't overdo it either, there is a reason why using StringBuilder is more efficient than simple String concatenation. And finally, keep your overall memory footprint and especially your old generation as small as possible. The more objects you keep the less the GC will perform.

Related reading:

  1. Major GCs – Separating Myth from Reality In a recent post we have shown how the Java...
  2. JDK6 Update 23 changes CMS Collection counters Stefan Frandl, Test Automation Team Lead at dynaTrace, recently tested...
  3. Behind the Scenes of Serialization in Java When building distributed applications one of the central performance-critical components...
  4. How to identify IE Add-Ons such as Skype that impact Web Site Performance I occasionally get invited to do JavaScript/AJAX Performance Workshops. Last...

More Stories By Michael Kopp

Michael Kopp has over 12 years of experience as an architect and developer in the Enterprise Java space. Before coming to CompuwareAPM dynaTrace he was the Chief Architect at GoldenSource, a major player in the EDM space. In 2009 he joined dynaTrace as a technology strategist in the center of excellence. He specializes application performance management in large scale production environments with special focus on virtualized and cloud environments. His current focus is how to effectively leverage BigData Solutions and how these technologies impact and change the application landscape.

@ThingsExpo Stories
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...