Hosted with ❤ by GitHub How to monitor the memory usage of Java Application using JConsoleĪfter running the main method open JConsole and connect it to the local Java Process. byte array – to expedite the memory leak we have a byte array of 10Mb.name – an optional variable representing the name of the dog. microchip ID – uniquely identifies the dog.The Dog.java class has three variables described below. The complete example is hosted on Github. Let’s consider a real-life example of a Dog Shelter where Dogs are added to the shelter and removed from the shelter when they are adopted. In the following section, we will consider the example of this kind of leak. However, if the code is already deployed there is no way to set the reference of unused objects to null. Some developer considers this leak as, not an “actual memory leak” because setting the reference to null would allow GC to reclaim the memory. The second kind of memory leak is mostly due to faulty logic in the program where the reference to unused objects is kept in the running code (even though the object will never be used again) which doesn’t allow the GC to reclaim the memory. The first kind of memory leak occurs when the reference to the object is no longer present in the running code but the Garbage Collector is still not able to free up space for these objects. An example code of this is posted here. Memory leaks caused by objects that are reachable from running code but won’t be used again.Memory leaks caused by objects that are unreachable from running code.Even though there is no official definition of a memory leak in Java we can broadly divide it into two categories for ease of understanding. The Reference to a Dog object – Buddy is set to null in the second part of the image hence it becomes eligible for GC.Ī memory leak is caused when the program fails to release unused memory which can lead to either unexpected results or application crash. Any object that doesn’t have a reference to it is eligible for Garbage collection as seen in the image below. In Java, the Garbage Collector (GC) is responsible for freeing up the memory utilized by unused objects. The deep dive into the memory monitoring tool of JConsole will allow us to see how the Heap memory is divided into different spaces and how the Garbage collector efficiently manages the memory of the Java Application. Afterward, we will connect the Java application to JConsole to compare the memory usage of the application with and without memory leaks. In this post, we will see example code of memory leak in Java. Detecting memory leak in Java using JConsole with example code
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |