
Java Memory Management
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
All prices
More details
Persons
Maaike is a software consultant and trainer with a passion for sharing her expertise to empower others in their careers. Her love for software development shows in the numerous software development projects she participated in and the many certifications she obtained. She has designed and delivered a broad spectrum of training courses catering to beginners and seasoned developers in Java, Python, C# and many other languages and frameworks. Next to that, she has authored multiple books and online courses through multiple platforms reaching over 500,000 learners across the globe.Kennedy Dr. Seán :
Seán Kennedy is a university lecturer with over 20 years of experience in teaching. He has a PhD in IT and is Oracle-certified in Java at the Professional level (OCP). In his daily work, he teaches Java on a bespoke master's program for a highly regarded software company. He has a YouTube channel called Let's Get Certified that teaches Java at all levels and prepares candidates for Java certification. He also has similar courses on Udemy. Outside of work, he enjoys tennis, walking, nature, reading, and TV.
Content
- Primitives and Objects in Java Memory
- Zooming in on the heap space
- Freeing the Memory with Garbage Collection
- Zooming in On The Metaspace
- Configuring and Monitoring the Memory Management of the JVM
- Avoiding Memory Leaks
1
Different Parts of the Java Memory
Do you know the phenomenon of having to restart an application to boost the performance of that application? If so, you may have experienced the outcome of poor memory management: the memory getting full and the application slowing down. This is not always why applications slow down - other causes such as processing data from a server or a bottleneck in the network, among other things, play a role - but memory management problems are a usual suspect of degrading application performance.
You've probably heard of memory in the field of computer science before. That makes sense because computers have memory and they use this memory to store and access data while running programs (which in their turn are data too!).
So, when does an application use memory? Well, for example, let's say you'd like to run an application that is going to process a huge video file. If you do this with your activity monitoring application (for example, Activity Monitor on macOS or Task Manager on Windows) open, you'll see that the used memory increases once you open the application and load the video. Memory is a finite resource on your computer and once your computer runs out of it, it becomes slow.
There are many ways to improve the performance of an application. A deeper understanding of how exactly this memory works is one of the ways that could help you improve the performance of your applications. Memory that is used efficiently by using good practices in coding is going to boost the performance of your application. So, coding well and being mindful of how the memory works should always be the first way to achieve high performance when it comes to memory management. There is another way in which Java memory management can be influenced and that is by configuring the Java Virtual Machine (JVM), which takes care of the Java memory. This is something that we'll cover in Chapter 6 when we're ready for it.
The efficient handling of Java memory is of crucial importance for the performance of a Java application. In Java, this is especially the case because it comes with expensive processes such as garbage collection, which again, we'll see later after gaining enough basic knowledge to comprehend it.
Memory management is also important for data integrity in a concurrent context. Don't worry if this sounds very complicated at the moment. By the end of this book, you'll understand what is meant by this.
So, to optimize the usage of our application's Java memory, we'll first need to understand what this memory looks like and gain knowledge of the basic processes with the memory. In this chapter, we'll do just that. We're going to explore the different parts of Java memory and how we use this in our day-to-day coding. You'll get a good overview of Java memory and you'll be ready for the deep dive that's coming in the next chapters. In order to do so, we'll cover the following topics:
- Understanding computer memory and Java memory
- Creating variables in Java
- Storing variables on the stack
- Creating objects in Java
- Storing objects on the heap
- Exploring the Metaspace
Technical requirements
The code for this chapter can be found on GitHub at PacktPublishing/B18762_Java-Memory-Management.
Understanding computer memory and Java memory
First things first - running applications, Java or not, requires computer memory. The application's memory is the physical memory of the computer. Having more knowledge about the memory of the computer is going to help in our understanding of Java memory. Therefore, let's discuss the concept of memory and Java memory in a bit more detail.
Computer memory
Chances are that you already know this, but just to reiterate: a computer has memory. This is the part of the computer that is used for storing information that is used for executing processes. We also call this the main memory or sometimes primary storage. An important point to make here is that this is different from computer storage, where long-term information is stored. This storage is long-term because the HDD storage stores the information magnetically and the SDD can be qualified as Electrically Erasable Programmable Read-Only Memory (EEPROM). They don't need constant power to persist the data. On the other hand, one common type of main memory, Random Access Memory (RAM), needs constant electricity power to persist data.
This can be compared to our human brains, at least partially. We have long-term and short-term memory. We use our long-term memory for our, well, memories - for example, a cherished childhood memory of your father pushing you around playfully in a wheelbarrow while your mother quoted from your most beloved storybook while you were wearing your favorite outfit that you had as a 3-year-old (magical, let's save the rest for my memoir or therapist). Then there's short-term memory, which is great when you want to remember the six digits for a two-step verification process and even better if you can't recall them a few minutes later.
Accessing the main memory
The computer, or actually the CPU of the computer, can access the main memory much faster than it can access the permanent storage space. In the main memory, programs are currently open and the data that they're using is being stored.
Maybe you can recall starting your computer and opening an app you use daily for the first time that day and realizing that it takes a few seconds to boot. If you close it, perhaps accidentally, and open it again right after closing it, it is a lot faster. The main memory works as some sort of cache or buffer, and this explains the phenomenon of the shorter load time the second time. The second time, it can open it from the main memory instead of from the storage, which proves, or at least supports, the point that the main memory is faster.
The great news is that you don't need to understand the tiniest details of the computer memory, but a rough overview will help.
Overview of the main memory
The most common part of the main memory is the RAM. The RAM is a huge part of what determines the performance of a computer. Running or active applications need RAM for storing and accessing data. This memory can be accessed very quickly by the applications and processes. If there is enough RAM available and if the Operating System (OS) does a great job of managing the RAM, your applications will reach their performance potential.
You can see how much RAM is available by having a look at your monitoring app. For me, that is Activity Monitor. As you can see in the following figure, my computer is using quite a bit of memory at the moment:
Figure 1.1 - Screenshot of Activity Monitor on macOS 12.5
I have sorted the processes from high memory to low. At the bottom, you can see a summary of the available memory and the memory used. To be honest, this seems a little high and I should probably investigate it after writing this chapter.
Why should I investigate this if I still have a lot of memory available? Well, if the RAM gets too full, the applications that are running can only do so very slowly. This is something you're likely to have experienced already when you've run more or heavier applications than your computer specifications allowed.
The RAM is volatile. This means that when you turn off the power, the information is gone. The main memory does not only consist of RAM. The Read-Only Memory (ROM) is part of the main memory too, but it's non-volatile. It contains instructions that the computer needs to start, so luckily this does not disappear when we turn the power off!
Fun fact
We refer to the main memory as RAM, which is very common terminology, but now you know it's technically incorrect! A fun fact indeed.
Java memory and the JVM
You may wonder if we are still going to cover Java memory - and yes, we are! The Java memory is somewhat similar to, but also different from, the computer's memory model. However, before we talk about Java memory, I'll need to explain what the JVM is. I really appreciate your patience, I must say.
The JVM
The JVM executes Java applications. Does that mean that the JVM understands Java? No, not at all! It understands bytecode - the .class files. This means the compiled Java programs. The code of some other languages, such as Kotlin, is compiled to JVM bytecode as well and can therefore be interpreted by the JVM. This is why they're sometimes referred to as JVM languages, such as Java, Kotlin, and Scala, among others.
The steps can be seen in Figure...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.
File format: ePUB
Copy protection: without DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Use a reader that can handle the file format ePUB, such as Adobe Digital Editions or FBReader – both free (see eBook Help).
- Tablet/Smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePUB works well for novels and non-fiction books – i.e., 'flowing' text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook does not use copy protection or Digital Rights Management
For more information, see our eBook Help page.