Reputation: 109
I am a newbie to Java. I understand what garbage collection and paging, swapping do in isolation. I wanted to understand how they relate to each other. Does GC cause paging or swapping? I know that the primary job of GC is to reclaim memory. But does it reclaim by paging or swapping if needed or is it not relevant to GC and is done by OS?
Upvotes: 3
Views: 2969
Reputation: 169
Actually, I am a newbie in Java world too. I come here because I get confused with this just like you. However, if you thinking about the mechanism of swapping, you may find the difference between swap and garbage collection. swapping is a behaviour of operator system. and garbage collection is a behaviour of Java jvm which is a process/thread of the system. So, swapping and garbage collection is different level thing. If memory is not enough, swapping will happen to figure out memory that unused temporary and then swapping out.
Above all, swapping may happen before full GC. and at the same time, garbage collection i.e. full gc. also may happen without swapping. A simple example is that: we config the JVM with a small heap size . bug we allocate a large buffer space, at this situation, full GC may happen and also OOM may happen.
Upvotes: 0
Reputation: 43987
To understand the relation, note that Java performs generational garbage collection. There is a young and and old generation of objects allocated on the heap. From the JVM's point of view, it will not care about swapping but use the heap size it was configured with. However, the heap size will of course dictate the swapping behaviour of the OS that manages the JVM process.
In the young generation's collection, only rather new objects are collected. These objects should not have been swapped out by the OS due to their recent allocation. Of course, if you chose a size bigger than your RAM for your young generation, swapping will be required even for collecting the young generation what will slow down your garbage collector.
In the tenured generation, the performance of garbage collection will firstly depend on the strategy for collection. Consider a naive algorithm that performs a full garbage collection. This algorithm will have to check the entire application's object graph what requires access to the entire JVM heap. Obviously, the entire heap should fit into the RAM. Otherwise, a lot of swapping will be required for garbage collection what will result in a bad performance. In reality, the collector will not check the entire object graph. However, it remains a good practise to choose a heap size that fits into your RAM in order to avoid excessive swapping when for example configuring a Java application's production server.
Upvotes: 3