+ All Categories
Home > Documents > Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM)...

Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM)...

Date post: 13-May-2020
Category:
Upload: others
View: 11 times
Download: 0 times
Share this document with a friend
37
Sat 1/6/2018 1 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN JAVA ...................................................................................3 WHERE STORAGE LIVES ........................................................................................................................................................................ 3 TYPES ..................................................................................................................................................................................................... 3 HIGH-PRECISION NUMBERS ................................................................................................................................................................... 4 JAVA (JVM) MEMORY MODEL ....................................................................................................................................................5 MEMORY MANAGEMENT IN JAVA YOUNG GENERATION ..................................................................................................................... 5 MEMORY MANAGEMENT IN JAVA OLD GENERATION .......................................................................................................................... 5 Stop the World Event ...................................................................................................................................................................... 5 Java Memory Model – Permanent Generation ........................................................................................................................... 6 Java Memory Model – Method Area............................................................................................................................................. 6 Java Memory Model – Memory Pool ............................................................................................................................................ 6 Java Memory Model – Runtime Constant Pool .......................................................................................................................... 6 Java Memory Model – Java Stack Memory ................................................................................................................................ 6 Memory Management in Java – Java Heap Memory Switches ............................................................................................... 6 MEMORY MANAGEMENT IN JAVA JAVA GARBAGE COLLECTION ......................................................................................................... 7 MEMORY MANAGEMENT IN JAVA JAVA GARBAGE COLLECTION TYPES ............................................................................................. 7 MEMORY MANAGEMENT IN JAVA JAVA GARBAGE COLLECTION MONITORING................................................................................... 8 jstat .................................................................................................................................................................................................... 8 Java VisualVM with Visual GC ...................................................................................................................................................... 9 JAVA GARBAGE COLLECTION TUNING ................................................................................................................................................. 10 INTRODUCTION..................................................................................................................................................................................... 11 1. Q1. What does the statement “memory is managed in Java” mean? ............................................................................................ 11 2. Q2. What is Garbage Collection and what are its advantages?...................................................................................................... 11 3. Q3. Are there any disadvantages of Garbage Collection? ............................................................................................................... 11 4. Q4. What is the meaning of the term “stop-the-world”? ................................................................................................................... 11 5. Q5. What are stack and heap? What is stored in each of these memory structures, and how are they interrelated?............ 11 6. Q6. What is generational garbage collection and what makes it a popular garbage collection approach? .............................. 12 7. Q7. Describe in detail how generational garbage collection works ................................................................................................ 12 8. Q8. When does an object become eligible for garbage collection? Describe how the GC collects an eligible object? .......... 13 9. Q9. How do you trigger garbage collection from Java code? .......................................................................................................... 13 10. Q10. What happens when there is not enough heap space to accommodate storage of new objects? .............................. 13 11. Q11. Is it possible to «resurrect» an object that became eligible for garbage collection?....................................................... 13 12. In Java, no variable can ever hold an object. A variable can only hold a reference to an object. ......................................... 14 TYPES OF REFERENCES IN JAVA : STRONG, SOFT, WEAK AND PHANTOM ....................................................................................... 16 Strong Reference .......................................................................................................................................................................... 16 Soft reference ................................................................................................................................................................................ 16 Weak reference ............................................................................................................................................................................. 17 Phantom reference........................................................................................................................................................................ 17 1) STRONG REFERENCES.................................................................................................................................................................... 17 2) SOFT REFERENCES......................................................................................................................................................................... 18 3) WEAK REFERENCES........................................................................................................................................................................ 20 4) PHANTOM REFERENCES ................................................................................................................................................................. 21 13. Q13. Suppose we have a circular reference (two objects that reference each other). Could such pair of objects become eligible for garbage collection and why? ..................................................................................................................................................... 22 14. Q14. How are strings represented in memory? ............................................................................................................................ 22 15. Q15. What is a StringBuilder and what are its use cases? What is the difference between appending a string to a StringBuilder and concatenating two strings with a + operator? How does StringBuilder differ from StringBuffer? ..................... 22 MEMORY LEAKS ................................................................................................................................................................................... 24 16. Memory Leak causes ........................................................................................................................................................................ 24 17. How does substring creates memory leak in Java ....................................................................................................................... 24 18. What is a thread local variable in Java? ......................................................................................................................................... 24 19. Static field holding object reference [esp final field]...................................................................................................................... 24 20. Circular and Complex Bi-Directional References.......................................................................................................................... 24 21. What is a thread local variable in Java? ......................................................................................................................................... 24
Transcript
Page 1: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

1

JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN JAVA ................................................................................... 3

WHERE STORAGE LIVES ........................................................................................................................................................................ 3 TYPES ..................................................................................................................................................................................................... 3 HIGH-PRECISION NUMBERS ................................................................................................................................................................... 4

JAVA (JVM) MEMORY MODEL .................................................................................................................................................... 5

MEMORY MANAGEMENT IN JAVA – YOUNG GENERATION ..................................................................................................................... 5 MEMORY MANAGEMENT IN JAVA – OLD GENERATION .......................................................................................................................... 5

Stop the World Event ...................................................................................................................................................................... 5 Java Memory Model – Permanent Generation ........................................................................................................................... 6 Java Memory Model – Method Area ............................................................................................................................................. 6 Java Memory Model – Memory Pool ............................................................................................................................................ 6 Java Memory Model – Runtime Constant Pool .......................................................................................................................... 6 Java Memory Model – Java Stack Memory ................................................................................................................................ 6 Memory Management in Java – Java Heap Memory Switches ............................................................................................... 6

MEMORY MANAGEMENT IN JAVA – JAVA GARBAGE COLLECTION ......................................................................................................... 7 MEMORY MANAGEMENT IN JAVA – JAVA GARBAGE COLLECTION TYPES ............................................................................................. 7 MEMORY MANAGEMENT IN JAVA – JAVA GARBAGE COLLECTION MONITORING ................................................................................... 8

jstat .................................................................................................................................................................................................... 8 Java VisualVM with Visual GC ...................................................................................................................................................... 9

JAVA GARBAGE COLLECTION TUNING ................................................................................................................................................. 10 INTRODUCTION ..................................................................................................................................................................................... 11

1. Q1. What does the statement “memory is managed in Java” mean? ............................................................................................ 11 2. Q2. What is Garbage Collection and what are its advantages? ...................................................................................................... 11 3. Q3. Are there any disadvantages of Garbage Collection? ............................................................................................................... 11 4. Q4. What is the meaning of the term “stop-the-world”? ................................................................................................................... 11 5. Q5. What are stack and heap? What is stored in each of these memory structures, and how are they interrelated? ............ 11 6. Q6. What is generational garbage collection and what makes it a popular garbage collection approach? .............................. 12 7. Q7. Describe in detail how generational garbage collection works ................................................................................................ 12 8. Q8. When does an object become eligible for garbage collection? Describe how the GC collects an eligible object? .......... 13 9. Q9. How do you trigger garbage collection from Java code? .......................................................................................................... 13 10. Q10. What happens when there is not enough heap space to accommodate storage of new objects? .............................. 13 11. Q11. Is it possible to «resurrect» an object that became eligible for garbage collection?....................................................... 13 12. In Java, no variable can ever hold an object. A variable can only hold a reference to an object. ......................................... 14

TYPES OF REFERENCES IN JAVA : STRONG, SOFT, WEAK AND PHANTOM ....................................................................................... 16 Strong Reference .......................................................................................................................................................................... 16 Soft reference ................................................................................................................................................................................ 16 Weak reference ............................................................................................................................................................................. 17 Phantom reference........................................................................................................................................................................ 17

1) STRONG REFERENCES .................................................................................................................................................................... 17 2) SOFT REFERENCES ......................................................................................................................................................................... 18 3) WEAK REFERENCES ........................................................................................................................................................................ 20 4) PHANTOM REFERENCES ................................................................................................................................................................. 21

13. Q13. Suppose we have a circular reference (two objects that reference each other). Could such pair of objects become

eligible for garbage collection and why? ..................................................................................................................................................... 22 14. Q14. How are strings represented in memory? ............................................................................................................................ 22 15. Q15. What is a StringBuilder and what are its use cases? What is the difference between appending a string to a StringBuilder and concatenating two strings with a + operator? How does StringBuilder differ from StringBuffer? ..................... 22

MEMORY LEAKS ................................................................................................................................................................................... 24 16. Memory Leak causes ........................................................................................................................................................................ 24 17. How does substring creates memory leak in Java ....................................................................................................................... 24 18. What is a thread local variable in Java? ......................................................................................................................................... 24 19. Static field holding object reference [esp final field] ...................................................................................................................... 24 20. Circular and Complex Bi-Directional References .......................................................................................................................... 24 21. What is a thread local variable in Java? ......................................................................................................................................... 24

Page 2: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

2

22. Unclosed) open streams ( file , network etc... ) ............................................................................................................................. 25 23. Unclosed connections ....................................................................................................................................................................... 25 24. HashSet with an incorrect hashCode() or equals, keep adding duplicates. .............................................................................. 25 25. What best practices you follow with Monitor and Fix Resource Leaks ...................................................................................... 25

GARBAGE COLLECTION ....................................................................................................................................................................... 25 26. Which statement is true? .................................................................................................................................................................. 25 27. At what point is the Bar object, created on line 6, eligible for garbage collection? ................................................................. 26 28. When is the Demo object eligible for garbage collection? ........................................................................................................... 27 29. After line 8 runs. how many objects are eligible for garbage collection? ................................................................................... 27 30. When is the Float object, created in line 3, eligible for garbage collection? .......................................................................... 28

GARABAGE COLLECTION RULE SAYS WHEN, AN OBJECT REFERENCE IS NULLYFY, THEN IT IS ELIGIBLE FOR GARBAGE COLLECTION.

............................................................................................................................................................................................................. 29 31. Garbage Collection? ......................................................................................................................................................................... 29 32. Memory quesiton? ............................................................................................................................................................................. 29 33. What allows the programmer to destroy an object x? .................................................................................................................. 30 34. When is the Float object, created in line 3, eligible for garbage collection? .......................................................................... 31 35. When is the B object, created in line 3, eligible for garbage collection? .................................................................................... 31 36. after line 11 runs, how many objects are eligible for garbage collection? Isolated objects .................................................... 32 37. The following code creates one array and one string object. How many references to those objects exist after the code executes? Is either object eligible for garbage collection? ....................................................................................................................... 32 38. How does a program destroy an object that it creates? ............................................................................................................... 32

SIB – STATIC INITIALIZATION BLOCK, STATIC VARIABLES AND STATIC METHODS ............................................................................. 32 Diagramatic representation of memory allocation of above program looks like this. .......................................................... 34

MAIN CLASS SIB ............................................................................................................................................................................. 35

STATICCOMPONENTS SIB .............................................................................................................................................................. 35

FROM STATICMETHOD .................................................................................................................................................................. 35

NON-STATIC MEMBERS AND THEIR MEMORY MANAGEMENT IN JAVA ............................................................................................... 35

Page 3: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

3

Java (JVM) Memory Model – Memory Management in Java

SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Where storage lives

It’s useful to visualize some aspects of how things are laid out while the program is running—in particular how memory is arranged. There are six different places to store data:

1. Registers. This is the fastest storage because it exists in a place different from that of other storage: inside the processor. However, the number of registers is severely limited, so registers are allocated by the compiler according to its needs. You don’t have direct control, nor do you see any evidence in your programs that registers even exist.

2. The stack. This lives in the general random-access memory (RAM) area, but has direct support from the processor via its stack pointer. The stack pointer is moved down to create new memory and moved up to release that memory. This is an extremely fast and efficient way to allocate storage, second only to registers. The Java compiler must know, while it is creating the program, the exact size and lifetime of all the data that is stored on the stack, because it must generate the code to move the stack pointer up and down. This constraint places limits on the flexibility of your programs, so while some Java storage exists on the stack—in particular, object references—Java objects themselves are not placed on the stack.

3. The heap. This is a general-purpose pool of memory (also in the RAM area) where all Java objects live. The nice thing about the heap is that, unlike the stack, the compiler doesn’t need to know how much storage it needs to allocate from the heap or how long that storage must stay on the heap. Thus, there’s a great deal of flexibility in using storage on the heap. Whenever you need to create an object, you simply write the code to create it by using new, and the storage is allocated on the heap when that code is executed. Of course there’s a price you pay for this flexibility. It takes more time to allocate heap storage than it does to allocate stack storage (if you even could create objects on the stack in Java, as you can in C++).

4. Static storage. “Static” is used here in the sense of “in a fixed location” (although it’s also in RAM). Static storage contains data that is available for the entire time a program is running. You can use the static keyword to specify that a particular element of an object is static, but Java objects themselves are never placed in static storage.

5. Constant storage. Constant values are often placed directly in the program code, which is safe since they can never change. Sometimes constants are cordoned off by themselves so that they can be optionally placed in read-only memory (ROM), in embedded systems.

6. Non-RAM storage. If data lives completely outside a program, it can exist while the program is not running, outside the control of the program. The two primary examples of this are streamed objects, in which objects are turned into streams of bytes, generally to be sent to another machine, and persistent objects, in which the objects are placed on disk so they will hold their state even when the program is terminated. The trick with these types of storage is turning the objects into something that can exist on the other medium, and yet can be resurrected into a regular RAM-based object when necessary. Java provides support for lightweight persistence, and future versions of Java might provide more complete solutions for persistence. Special case: primitive types

types

One group of types, which you’ll use quite often in your programming, gets special treatment. You can think of these as “primitive” types. The reason for the special treatment is that to create an object with new—especially a small, simple variable—isn’t very efficient, because new places objects on the heap. For these types Java falls back on the approach taken by C and C++. That is, instead of creating the variable by using new, an “automatic” variable is created that is not a reference. The variable holds the value, and it’s placed on the stack, so it’s much more efficient.

Java determines the size of each primitive type. These sizes don’t change from one machine architecture to another as they do in most languages. This size invariance is one reason Java programs are portable.

Primitive type Size Minimum Maximum Wrapper type

Page 4: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

4

boolean — — — Boolean char 16-bit Unicode 0 Unicode 216- 1 Character

byte 8-bit -1+1Byte short 16-bit -2+215—1 Short int 32-bit -2+231—1 Integer

long 64-bit -2+263—1 Long float 32-bit IEEE7IEEE7Float double 64-bit IEEE7IEEE7Double

void — — — Void

All numeric types are signed, so don’t look for unsigned types.

The size of the boolean type is not explicitly specified; it is only defined to be able to take the literal values true or false.

The “wrapper” classes for the primitive data types allow you to make a nonprimitive object on the heap to represent that primitive type. For example:

char c = 'x';

Character C = new Character(c);

Or you could also use: Character C = new Character('x');

High-precision numbers

Java includes two classes for performing high-precision arithmetic: BigInteger and BigDecimal. Although these approximately fit into the same category as the “wrapper” classes, neither one has a primitive analogue.

Both classes have methods that provide analogues for the operations that you perform on primitive types. That is, you can do anything with a BigInteger or BigDecimal that you can with an int or float, it’s just that you must use method calls instead of operators. Also, since there’s more involved, the operations will be slower. You’re exchanging speed for accuracy.

BigInteger supports arbitrary-precision integers. This means that you can accurately represent integral values of any size without losing any information during operations.

BigDecimal is for arbitrary-precision fixed-point numbers; you can use these for accurate monetary calculations, for example.

Consult the JDK documentation for details about the constructors and methods you can call for these two classes.

Understanding JVM Memory Model, Java Memory Management are very important if you want to understand the working of Java

Garbage Collection. Today we will look into memory management in java, different parts of JVM memory and how to monitor and

perform garbage collection tuning.

Page 5: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

5

Java (JVM) Memory Model

As you can see in the above image, JVM memory is divided into separate parts. At broad level, JVM Heap memory is physically

divided into two parts – Young Generation and Old Generation.

Memory Management in Java – Young Generation

Young generation is the place where all the new objects are created. When young generation is filled, garbage collection is performed.

This garbage collection is called Minor GC. Young Generation is divided into three parts – Eden Memory and two Survivor

Memory spaces.

Important Points about Young Generation Spaces:

Most of the newly created objects are located in the Eden memory space.

When Eden space is filled with objects, Minor GC is performed and all the survivor objects are moved to one of the survivor

spaces.

Minor GC also checks the survivor objects and move them to the other survivor space. So at a time, one of the survivor space

is always empty.

Objects that are survived after many cycles of GC, are moved to the Old generation memory space. Usually it’s done by setting

a threshold for the age of the young generation objects before they become eligible to promote to Old generation.

Memory Management in Java – Old Generation

Old Generation memory contains the objects that are long lived and survived after many rounds of Minor GC. Usually garbage

collection is performed in Old Generation memory when it’s full. Old Generation Garbage Collection is called Major GC and usually

takes longer time.

Stop the World Event All the Garbage Collections are “Stop the World” events because all application threads are stopped until the operation completes.

Since Young generation keeps short-lived objects, Minor GC is very fast and the application doesn’t get affected by this.

However Major GC takes longer time because it checks all the live objects. Major GC should be minimized because it will make your

application unresponsive for the garbage collection duration. So if you have a responsive application and there are a lot of Major

Garbage Collection happening, you will notice timeout errors.

Page 6: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

6

The duration taken by garbage collector depends on the strategy used for garbage collection. That’s why it’s necessary to monitor and

tune the garbage collector to avoid timeouts in the highly responsive applications.

Java Memory Model – Permanent Generation Permanent Generation or “Perm Gen” contains the application metadata required by the JVM to describe the classes and methods used

in the application. Note that Perm Gen is not part of Java Heap memory.

Perm Gen is populated by JVM at runtime based on the classes used by the application. Perm Gen also contains Java SE library

classes and methods. Perm Gen objects are garbage collected in a full garbage collection.

Java Memory Model – Method Area Method Area is part of space in the Perm Gen and used to store class structure (runtime constants and static variables) and code for

methods and constructors.

Java Memory Model – Memory Pool Memory Pools are created by JVM memory managers to create a pool of immutable objects, if implementation supports it. String Pool

is a good example of this kind of memory pool. Memory Pool can belong to Heap or Perm Gen, depending on the JVM memory

manager implementation.

Java Memory Model – Runtime Constant Pool Runtime constant pool is per-class runtime representation of constant pool in a class. It contains class runtime constants and static

methods. Runtime constant pool is the part of method area.

Java Memory Model – Java Stack Memory Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other

objects in the heap that are getting referred from the method. You should read Difference between Stack and Heap Memory.

Memory Management in Java – Java Heap Memory Switches Java provides a lot of memory switches that we can use to set the memory sizes and their ratios. Some of the commonly used memory

switches are:

VM SWITCH VM SWITCH DESCRIPTION

-Xms For setting the initial heap size when JVM starts

-Xmx For setting the maximum heap size.

-Xmn For setting the size of the Young Generation, rest of the space goes for Old Generation.

-XX:PermGen For setting the initial size of the Permanent Generation memory

-XX:MaxPermGen For setting the maximum size of Perm Gen

Page 7: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

7

-XX:SurvivorRatio For providing ratio of Eden space and Survivor Space, for example if Young Generation size is 10m and VM switch is -XX:SurvivorRatio=2 then 5m will be reserved for Eden Space and 2.5m each for both the Survivor spaces. The default value is 8.

-XX:NewRatio For providing ratio of old/new generation sizes. The default value is 2.

Most of the times, above options are sufficient, but if you want to check out other options too then please check JVM Options

Official Page.

Memory Management in Java – Java Garbage Collection

Java Garbage Collection is the process to identify and remove the unused objects from the memory and free space to be allocated to

objects created in the future processing. One of the best feature of java programming language is the automatic garbage collection,

unlike other programming languages such as C where memory allocation and deallocation is a manual process.

Garbage Collector is the program running in the background that looks into all the objects in the memory and find out objects that

are not referenced by any part of the program. All these unreferenced objects are deleted and space is reclaimed for allocation to other

objects.

One of the basic way of garbage collection involves three steps:

1. Marking: This is the first step where garbage collector identifies which objects are in use and which ones are not in use.

2. Normal Deletion: Garbage Collector removes the unused objects and reclaim the free space to be allocated to other objects.

3. Deletion with Compacting: For better performance, after deleting unused objects, all the survived objects can be moved to be

together. This will increase the performance of allocation of memory to newer objects.

There are two problems with simple mark and delete approach.

1. First one is that it’s not efficient because most of the newly created objects will become unused

2. Secondly objects that are in-use for multiple garbage collection cycle are most likely to be in-use for future cycles too.

The above shortcomings with the simple approach is the reason that Java Garbage Collection is Generational and we have Young

Generation and Old Generation spaces in the heap memory. I have already explained above how objects are scanned and moved

from one generational space to another based on the Minor GC and Major GC.

Memory Management in Java – Java Garbage Collection Types

There are five types of garbage collection types that we can use in our applications. We just need to use JVM switch to enable the

garbage collection strategy for the application. Let’s look at each of them one by one.

1. Serial GC (-XX:+UseSerialGC): Serial GC uses the simple mark-sweep-compact approach for young and old generations

garbage collection i.e Minor and Major GC.

Serial GC is useful in client-machines such as our simple stand alone applications and machines with smaller CPU. It is good

for small applications with low memory footprint.

Page 8: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

8

2. Parallel GC (-XX:+UseParallelGC): Parallel GC is same as Serial GC except that is spawns N threads for young generation

garbage collection where N is the number of CPU cores in the system. We can control the number of threads using -

XX:ParallelGCThreads=n JVM option.

Parallel Garbage Collector is also called throughput collector because it uses multiple CPUs to speed up the GC performance.

Parallel GC uses single thread for Old Generation garbage collection.

3. Parallel Old GC (-XX:+UseParallelOldGC): This is same as Parallel GC except that it uses multiple threads for both Young

Generation and Old Generation garbage collection.

4. Concurrent Mark Sweep (CMS) Collector (-XX:+UseConcMarkSweepGC): CMS Collector is also referred as concurrent

low pause collector. It does the garbage collection for Old generation. CMS collector tries to minimize the pauses due to

garbage collection by doing most of the garbage collection work concurrently with the application threads.

CMS collector on young generation uses the same algorithm as that of the parallel collector. This garbage collector is suitable

for responsive applications where we can’t afford longer pause times. We can limit the number of threads in CMS collector

using -XX:ParallelCMSThreads=n JVM option.

5. G1 Garbage Collector (-XX:+UseG1GC): The Garbage First or G1 garbage collector is available from Java 7 and it’s long

term goal is to replace the CMS collector. The G1 collector is a parallel, concurrent, and incrementally compacting low-pause

garbage collector.

Garbage First Collector doesn’t work like other collectors and there is no concept of Young and Old generation space. It

divides the heap space into multiple equal-sized heap regions. When a garbage collection is invoked, it first collects the region

with lesser live data, hence “Garbage First”. You can find more details about it at Garbage-First Collector Oracle

Documentation.

Memory Management in Java – Java Garbage Collection Monitoring

We can use Java command line as well as UI tools for monitoring garbage collection activities of an application. For my example, I

am using one of the demo application provided by Java SE downloads.

If you want to use the same application, go to Java SE Downloads page and download JDK 7 and JavaFX Demos and Samples.

The sample application I am using is Java2Demo.jar and it’s present in jdk1.7.0_55/demo/jfc/Java2D directory.

However this is an optional step and you can run the GC monitoring commands for any java application.

Command used by me to start the demo application is:

pankaj@Pankaj:~/Downloads/jdk1.7.0_55/demo/jfc/Java2D$ java -Xmx120m -Xms30m -Xmn10m -XX:PermSize=20m -XX:MaxPermSize=20m -XX:+UseSerialGC -jar Java2Demo.jar jstat

We can use jstat command line tool to monitor the JVM memory and garbage collection activities. It ships with standard JDK, so

you don’t need to do anything else to get it.

For executing jstat you need to know the process id of the application, you can get it easily using ps -eaf | grep

java command.

Page 9: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

9

pankaj@Pankaj:~$ ps -eaf | grep Java2Demo.jar 501 9582 11579 0 9:48PM ttys000 0:21.66 /usr/bin/java -Xmx120m -Xms30m -Xmn10m -XX:PermSize=20m -XX:MaxPermSize=20m -XX:+UseG1GC -jar Java2Demo.jar 501 14073 14045 0 9:48PM ttys002 0:00.00 grep Java2Demo.jar

So the process id for my java application is 9582. Now we can run jstat command as shown below.

pankaj@Pankaj:~$ jstat -gc 9582 1000 S0C S1C S0U S1U EC EU OC OU PC PU YGC YGCT FGC FGCT GCT 1024.0 1024.0 0.0 0.0 8192.0 7933.3 42108.0 23401.3 20480.0 19990.9 157 0.274 40 1.381 1.654 1024.0 1024.0 0.0 0.0 8192.0 8026.5 42108.0 23401.3 20480.0 19990.9 157 0.274 40 1.381 1.654 1024.0 1024.0 0.0 0.0 8192.0 8030.0 42108.0 23401.3 20480.0 19990.9 157 0.274 40 1.381 1.654 1024.0 1024.0 0.0 0.0 8192.0 8122.2 42108.0 23401.3 20480.0 19990.9 157 0.274 40 1.381 1.654 1024.0 1024.0 0.0 0.0 8192.0 8171.2 42108.0 23401.3 20480.0 19990.9 157 0.274 40 1.381 1.654 1024.0 1024.0 48.7 0.0 8192.0 106.7 42108.0 23401.3 20480.0 19990.9 158 0.275 40 1.381 1.656 1024.0 1024.0 48.7 0.0 8192.0 145.8 42108.0 23401.3 20480.0 19990.9 158 0.275 40 1.381 1.656

The last argument for jstat is the time interval between each output, so it will print memory and garbage collection data every 1

second.

Let’s go through each of the columns one by one.

S0C and S1C: This column shows the current size of the Survivor0 and Survivor1 areas in KB.

S0U and S1U: This column shows the current usage of the Survivor0 and Survivor1 areas in KB. Notice that one of the

survivor areas are empty all the time.

EC and EU: These columns show the current size and usage of Eden space in KB. Note that EU size is increasing and as soon

as it crosses the EC, Minor GC is called and EU size is decreased.

OC and OU: These columns show the current size and current usage of Old generation in KB.

PC and PU: These columns show the current size and current usage of Perm Gen in KB.

YGC and YGCT: YGC column displays the number of GC event occurred in young generation. YGCT column displays the

accumulated time for GC operations for Young generation. Notice that both of them are increased in the same row where EU

value is dropped because of minor GC.

FGC and FGCT: FGC column displays the number of Full GC event occurred. FGCT column displays the accumulated time

for Full GC operations. Notice that Full GC time is too high when compared to young generation GC timings.

GCT: This column displays the total accumulated time for GC operations. Notice that it’s sum of YGCT and FGCT column

values.

The advantage of jstat is that it can be executed in remote servers too where we don’t have GUI. Notice that sum of S0C, S1C and EC

is 10m as specified through -Xmn10m JVM option.

Java VisualVM with Visual GC

If you want to see memory and GC operations in GUI, then you can use jvisualvm tool. Java VisualVM is also part of JDK, so

you don’t need to download it separately.

Page 10: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

10

Just run jvisualvm command in the terminal to launch the Java VisualVM application. Once launched, you need to

install Visual GC plugin from Tools -< Plugins option, as shown in below image.

After installing Visual GC, just open the application from the left side column and head over to Visual GCsection. You will get an

image of JVM memory and garbage collection details as shown in below image.

Java Garbage Collection Tuning

Java Garbage Collection Tuning should be the last option you should use for increasing the throughput of your application and only when you see drop in performance because of longer GC timings causing application timeout.

If you see java.lang.OutOfMemoryError: PermGen space errors in logs, then try to monitor and

increase the Perm Gen memory space using -XX:PermGen and -XX:MaxPermGen JVM options. You might also try

using -XX:+CMSClassUnloadingEnabled and check how it’s performing with CMS Garbage collector.

If you are see a lot of Full GC operations, then you should try increasing Old generation memory space.

Page 11: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

11

Overall garbage collection tuning takes a lot of effort and time and there is no hard and fast rule for that. You would need to try different options and compare them to find out the best one suitable for your application.

That’s all for Java Memory Model, Memory Management in Java and Garbage Collection, I hope it helps you in understanding JVM memory and garbage collection process.

Introduction

In this article, we’ll explore some memory management questions that frequently pop up during Java developer interviews. Memory management is an area that not so many developers are familiar with.

In fact, developers don’t generally have to deal with this concept directly – as the JVM takes care of the nitty-gritty details. Unless something is going seriously wrong, even seasoned developers may not have accurate information about memory management at their fingertips.

On the other hand, these concepts are actually quite prevalent in interviews – so let’s jump right in.

1. Q1. What does the statement “memory is managed in Java” mean?

Memory is the key resource an application requires to run effectively and like any resource, it is scarce. As such, its allocation and deallocation to and from applications or different parts of an application require a lot of care and consideration.

However, in Java, a developer does not need to explicitly allocate and deallocate memory – the JVM and more specifically the Garbage Collector – has the duty of handling memory allocation so that the developer doesn’t have to.

This is contrary to what happens in languages like C where a programmer has direct access to memory and literally references memory cells in his code, creating a lot of room for memory leaks.

2. Q2. What is Garbage Collection and what are its advantages?

Garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.

An in-use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

The biggest advantage of garbage collection is that it removes the burden of manual memory allocation/deallocation from us so that we can focus on solving the problem at hand.

3. Q3. Are there any disadvantages of Garbage Collection?

Yes. Whenever the garbage collector runs, it has an effect on the application’s performance. This is because all other threads in the application have to be stopped to allow the garbage collector thread to effectively do its work.

Depending on the requirements of the application, this can be a real problem that is unacceptable by the client. However, this problem can be greatly reduced or even eliminated through skillful optimization and garbage collector tuning and using different GC algorithms.

4. Q4. What is the meaning of the term “stop-the-world”?

When the garbage collector thread is running, other threads are stopped, meaning the application is stopped momentarily. This is analogous to house cleaning or fumigation where occupants are denied access until the process is complete.

Depending on the needs of an application, “stop the world” garbage collection can cause an unacceptable freeze. This is why it is important to do garbage collector tuning and JVM optimization so that the freeze encountered is at least acceptable.

5. Q5. What are stack and heap? What is stored in each of these memory structures, and how are they interrelated?

The stack is a part of memory that contains information about nested method calls down to the current position in the

Page 12: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

12

program. It also contains all local variables and references to objects on the heap defined in currently executing methods.

This structure allows the runtime to return from the method knowing the address whence it was called, and also clear all local variables after exiting the method. Every thread has its own stack.

The heap is a large bulk of memory intended for allocation of objects. When you create an object with

the newkeyword, it gets allocated on the heap. However, the reference to this object lives on the stack.

6. Q6. What is generational garbage collection and what makes it a popular garbage collection approach?

Generational garbage collection can be loosely defined as the strategy used by the garbage collector where the heap is divided into a number of sections called generations, each of which will hold objects according to their “age” on the heap.

Whenever the garbage collector is running, the first step in the process is called marking. This is where the garbage collector identifies which pieces of memory are in use and which are not. This can be a very time-consuming process if all objects in a system must be scanned.

As more and more objects are allocated, the list of objects grows and grows leading to longer and longer garbage collection time. However, empirical analysis of applications has shown that most objects are short-lived.

With generational garbage collection, objects are grouped according to their “age” in terms of how many garbage collection cycles they have survived. This way, the bulk of the work spread across various minor and major collection cycles.

Today, almost all garbage collectors are generational. This strategy is so popular because, over time, it has proven to be the optimal solution.

7. Q7. Describe in detail how generational garbage collection works

To properly understand how generational garbage collection works, it is important to first remember how Java

heap is structured to facilitate generational garbage collection.

The heap is divided up into smaller spaces or generations. These spaces are Young Generation, Old or Tenured Generation, and Permanent Generation.

The young generation hosts most of the newly created objects. An empirical study of most

applications shows that majority of objects are quickly short lived and therefore, soon become eligible for collection. Therefore, new objects start their journey here and are only “promoted” to the old generation space after they have attained a certain “age”.

The term “age” in generational garbage collection refers to the number of collection cycles the object

has survived.

The young generation space is further divided into three spaces: an Eden space and two survivor spaces such as Survivor 1 (s1) and Survivor 2 (s2).

The old generation hosts objects that have lived in memory longer than a certain “age”. The

objects that survived garbage collection from the young generation are promoted to this space. It is generally larger than the young generation. As it is bigger in size, the garbage collection is more expensive and occurs less frequently than in the young generation.

The permanent generation or more commonly called, PermGen, contains metadata

required by the JVM to describe the classes and methods used in the application. It also contains the string

pool for storing interned strings. It is populated by the JVM at runtime based on classes in use by the application. In addition, platform library classes and methods may be stored here.

First, any new objects are allocated to the Eden space. Both survivor spaces start out empty. When the

Eden space fills up, a minor garbage collection is triggered. Referenced objects are moved to the first survivor space. Unreferenced objects are deleted.

During the next minor GC, the same thing happens to the Eden space. Unreferenced objects are deleted and

Page 13: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

13

referenced objects are moved to a survivor space. However, in this case, they are moved to the second survivor space (S1).

In addition, objects from the last minor GC in the first survivor space (S0) have their age incremented and are moved to S1. Once all surviving objects have been moved to S1, both S0 and Eden space are cleared. At this point, S1 contains objects with different ages.

At the next minor GC, the same process is repeated. However this time the survivor spaces switch. Referenced objects are moved to S0 from both Eden and S1. Surviving objects are aged. Eden and S1 are cleared.

After every minor garbage collection cycle, the age of each object is checked. Those that have reached a certain arbitrary age, for example, 8, are promoted from the young generation to the old or tenured generation. For all subsequent minor GC cycles, objects will continue to be promoted to the old generation space.

8. Q8. When does an object become eligible for garbage collection? Describe how the GC collects an eligible object?

An object becomes eligible for Garbage collection or GC if it is not reachable from any live threads or by any static references.

The most straightforward case of an object becoming eligible for garbage collection is if all its references are null. Cyclic dependencies without any live external reference are also eligible for GC. So if object A references object B and object B references Object A and they don’t have any other live reference then both Objects A and B will be eligible for Garbage collection.

Another obvious case is when a parent object is set to null. When a kitchen object internally references a fridge object and a sink object, and the kitchen object is set to null, both fridge and sink will become eligible for garbage collection alongside their parent, kitchen.

9. Q9. How do you trigger garbage collection from Java code?

You, as Java programmer, can not force garbage collection in Java; it will only trigger if JVM thinks

it needs a garbage collection based on Java heap size.

Before removing an object from memory garbage collection thread invokes finalize()method of that object and gives an opportunity to perform any sort of cleanup required. You can also invoke this method of an object code, however, there is no guarantee that garbage collection will occur when you call this method.

Additionally, there are methods like System.gc() and Runtime.gc() which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.

10. Q10. What happens when there is not enough heap space to accommodate storage of new objects?

If there is no memory space for creating a new object in Heap, Java Virtual Machine

throws OutOfMemoryErroror more specifically java.lang.OutOfMemoryError heap space.

11. Q11. Is it possible to «resurrect» an object that became eligible for garbage collection?

When an object becomes eligible for garbage collection, the GC has to run the finalize method on it.

The finalizemethod is guaranteed to run only once, thus the GC flags the object as finalized and gives it a rest until

the next cycle.

In the finalize method you can technically “resurrect” an object, for example, by assigning it to a static field. The

object would become alive again and non-eligible for garbage collection, so the GC would not collect it during the next cycle.

The object, however, would be marked as finalized, so when it would become eligible again, the finalize method would not be called. In essence, you can turn this “resurrection” trick only once for the lifetime of the object. Beware that this ugly hack should be used only if you really know what you’re doing — however, understanding this trick gives some insight into how the GC works.

Page 14: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

14

12. In Java, no variable can ever hold an object. A variable can only hold a reference to an object.

Objects are actually created by an operator called new, which creates an object and returns a reference to that object. For example, assuming that std is a variable of type Student, declared as above, the assignment statement

std = new Student();

would create a new object which is an instance of the class Student, and it would store a reference to that object in the variable std. The value of the variable is a reference to the object, not the object itself. It is not quite true, then, to say that the object is the "value of the variable std" (though sometimes it is hard to avoid using this terminology). It is

certainly not at all true to say that the object is "stored in the variable std. " The proper terminology is that "the

variable std refers to the object," and I will try to stick to that terminology as much as possible.

So, suppose that the variable std refers to an object belonging to the class Student. That object has instance variables name, test1, test2, and test3. These instance variables can be referred to as std. name, std. test1, std. test2, and std. test3. This follows the usual naming convention that when B is part of A, then the full name of B is a. b. For example, a program might include the lines

System.out.println("Hello, " + std. name

+ ". Your test grades are:");

System.out.println(std. test1);

System.out.println(std. test2);

System.out.println(std. test3);

This would output the name and test grades from the object to which std refers. Similarly, std can be used to call the getAverage() instance method in the object by saying std. getAverage(). To print out the student's average, you could say:

System.out.println( "Your average is " + std. getAverage() );

More generally, you could use std. name any place where a variable of type String is legal. You can use it in expressions. You can assign a value to it. You can even use it to call subroutines from the String class. For example, std. name. length() is the number of characters in the student's name.

It is possible for a variable like std, whose type is given by a class, to refer to no object at all. We say in this case that std holds a null reference. The null reference is written in Java as "null". You can store a null reference in the variable std by saying

std = null;

and you could test whether the value of std is null by testing if (std == null) . . .

If the value of a variable is null, then it is, of course, illegal to refer to instance variables or instance methods through that variable -- since there is no object, and hence no instance variables to refer to. For example, if the value of the variable std is null, then it would be illegal to refer to std. test1. If your program attempts to use a null reference illegally like this, the result is an error called a null pointer exception.

Let's look at a sequence of statements that work with objects:

Student std, std1, // Declare four variables of

std2, std3; // type Student.

std = new Student(); // Create a new object belonging

// to the class Student, and

// store a reference to that

// object in the variable std.

std1 = new Student(); // Create a second Student object

// and store a reference to

// it in the variable std1.

Page 15: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

15

std2 = std1; // Copy the reference value in std // into the variable std2.

std3 = null; // Store a null reference in the

// variable std3.

std. name = "John Smith"; // Set values of some instance variables.

std1.name = "Mary Jones";

// (Other instance variables have default

// initial values of zero.)

After the computer executes these statements, the situation in the computer's memory looks like this:

This picture shows variables as little boxes, labeled with the names of the variables. Objects are shown as boxes with round corners. When a variable contains a reference to an object, the value of that variable is shown as an arrow pointing to the object. The variable std3, with a value of null, doesn't point anywhere. The arrows from std1 and std2 both point to the same object. This illustrates a Very Important Point:

When one object variable is assigned to another, only a reference is copied. The object referred to is not copied.

When the assignment "std2 = std1;" was executed, no new object was created. Instead, std2 was set to refer to the very same object that std1 refers to. This has some consequences that might be surprising. For example, std1.name and std2.name refer to exactly the same variable, namely the instance variable in the object that both std1 and std2 refer to. After the string "Mary Jones" is assigned to the variable std1.name, it is also be true that the value of std2.name is "Mary Jones". There is a potential for a lot of confusion here, but you can help protect yourself from it if you keep telling yourself, "The object is not in the variable. The variable just holds a pointer to the object."

You can test objects for equality and inequality using the operators == and !=, but here again, the semantics are different from what you are used to. When you make a test "if (std1 == std2)", you are testing whether the values stored in std1 and std2 are the same. But the values are references to objects, not objects. So, you are testing whether std1 and std2 refer to the same object, that is, whether they point to the same location in memory. This is fine, if its what you want to do. But sometimes, what you want to check is whether the instance variables in the objects have the same values. To do that, you would need to ask whether

"std1.test1 == std2.test1 && std1.test2 == std2.test2 && std1.test3 == std2.test3 && std1.name. equals(std2.name)"

Page 16: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

16

I've remarked previously that Strings are objects, and I've shown the strings "Mary Jones" and "John Smith" as objects in the above illustration. A variable of type String can only hold a reference to a string, not the string itself. It could also hold the value null, meaning that it does not refer to any string at all. This explains why using the == operator to test strings for equality is not a good idea. Suppose that greeting is a variable of type String, and that the string it refers to is "Hello". Then would the test greeting == "Hello" be true? Well, maybe, maybe not. The variable greeting and the String literal "Hello" each refer to a string that contains the characters H-e-l-l-o. But the strings could still be different objects, that just happen to contain the same characters. The function greeting.equals("Hello") tests whether greeting and "Hello" contain the same characters, which is almost certainly the question you want to ask. The expression greeting == "Hello" tests whether greeting and "Hello" contain the same characters stored in the same memory location.

Types Of References In Java : Strong, Soft, Weak And Phantom

Much as memory is managed in Java, an engineer may need to perform as much optimization as possible to minimize

latency and maximize throughput, in critical applications. Much as it is impossible to explicitly control

when garbage collection is triggered in the JVM, it is possible to influence how it occurs as

regards the objects we have created. Java provides us with reference objects to control the relationship between the objects we create and the garbage collector.

Strong Reference

By default, every object we create in a Java program is strongly referenced by a variable: 1 StringBuilder sb = new StringBuilder();

In the above snippet, the new keyword creates a new StringBuilder object and stores it on the heap. The

variable sb then stores a strong reference to this object. What this means for the garbage collector is that the

particular StringBuilder object is not eligible for collection at all due to a strong reference held to it by sb. The story

only changes when we nullify sb like this:

1 sb = null;

After calling the above line, the object will then be eligible for collection.

We can change this relationship between the object and the garbage collector by explicitly wrapping it inside another

reference object which is located inside java.lang.ref package.

Soft reference

can be created to the above object like this: 1 2 3

StringBuilder sb = new StringBuilder(); SoftReference<StringBuilder> sbRef = new SoftReference<>(sb); sb = null;

In the above snippet, we have created two references to the StringBuilder object. The first line creates a strong

reference sb and the second line creates a soft reference sbRef. The third line should make the object eligible

for collection but the garbage collector will postpone collecting it because of sbRef.

The story will only change when memory becomes tight and the JVM is on the brink of throwing

an OutOfMemory error. In other words, objects with only soft references are collected as a last resort to recover

memory.

Page 17: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

17

Weak reference sb = null; // StringBuilder object only has a weak reference

can be created in a similar manner using WeakReference class. When sb is set to null and

the StringBuilder object only has a weak reference, the JVM’s garbage collector will have absolutely no

compromise and immediately collect the object at the very next cycle.

Phantom reference

is similar to a weak reference and an object with only phantom references will be collected without waiting. However, phantom references are enqueued as soon as their objects are collected. We can poll the reference queue to know exactly when the object was collected.

pramodbablad March 1, 2015 5

One of the beauty of the Java language is that it doesn’t put burden of memory management on the programmers. Java automatically manages the memory on the behalf of the programmers. Java programmers need not to worry about freeing the memory after the objects are no more required. Garbage Collector Thread does this for you.

This thread is responsible for sweeping out unwanted objects from the memory. But, you have no control over garbage collector thread. You can’t make it to run whenever you want. It is up to JVM which decides when to run garbage collector thread. But, with the introduction of java. lang.ref classes, you can have little control over when

your objects will be garbage collected.

Depending upon how objects are garbage collected, references to those objects in java are grouped into 4 types. They are,

1) Strong References

2) Soft References

3) Weak References

4) Phantom References

Let’s discuss these reference types in detail.

1) Strong References

These type of references we use daily while writing the code. Any object in the memory which has active strong reference is not eligible for garbage collection. For example, in the below program, reference variable ‘a’ is a strong

reference which is pointing to class A-type object. At this point of time, this object can’t be garbage collected as it has strong reference.

class A { //Class A } public class MainClass { public static void main(String[] args) { A a = new A(); //Strong Reference a = null; //Now, object to which 'a' is pointing earlier is eligible for garbage collection. } }

If you make reference ‘a’ to point to null like in Line 12, then, object to which ‘a’ is pointing earlier will become eligible

for garbage collection. Because, it will have no active references pointing to it. This object is most likely to be garbage collected when garbage collector decides to run.

Page 18: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

18

Look at the below picture for more precise understanding.

2) Soft References

The objects which are softly referenced will not be garbage collected (even though they are available for garbage collection) until JVM badly needs memory. These objects will be cleared from the memory only if JVM runs out of memory. You can create a soft reference to an existing object by using java. lang.ref.SoftReference class. Below

is the code example on how to create a soft reference.

class A { //A Class } public class MainClass { public static void main(String[] args) { A a = new A(); //Strong Reference //Creating Soft Reference to A-type object to which 'a' is also pointing SoftReference<A> softA = new SoftReference<A>(a); a = null; //Now, A-type object to which 'a' is pointing earlier is eligible for garbage collection. But, it will be garbage collected only when JVM needs memory. a = softa. get(); //You can retrieve back the object which has been softly referenced } }

In the above example, you create two strong references – ‘a‘ and ‘softA‘. ‘a’ is pointing to A-type object and ‘softA’ is

pointing to SoftReference type object. This SoftReference type object is internally referring to A-type object to which

Page 19: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

19

‘a’ is also pointing. When ‘a’ is made to point to null, object to which ‘a’ is pointing earlier becomes eligible for garbage collection. But, it will be garbage collected only when JVM needs memory. Because, it is softly referenced by ‘softA’ object.

Look at the below picture for more clarity.

One more use of SoftReference class is that you can retrieve back the object which has been softly referenced. It will be done by using get() method. This method returns reference to the object if object is not cleared from the

memory. If object is cleared from the memory, it will return null.

Page 20: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

20

3) Weak References

JVM ignores the weak references. That means objects which has only week references are eligible for garbage

collection. They are likely to be garbage collected when JVM runs garbage collector thread. JVM doesn’t show any regard for weak references.

Below is the code which shows how to create weak references.

class A { //A Class } public class MainClass { public static void main(String[] args) { A a = new A(); //Strong Reference //Creating Weak Reference to A-type object to which 'a' is also pointing. WeakReference<A> weakA = new WeakReference<A>(a); a = null; //Now, A-type object to which 'a' is pointing earlier is available for garbage collection. a = weaka. get(); //You can retrieve back the object which has been weakly referenced. } }

Look at the below picture for more clear understanding.

Page 21: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

21

You may think that what is the use of creating weak references if they are ignored by the JVM, Use of weak reference is that you can retrieve back the weakly referenced object if it is not yet removed from the memory. This is done using get() method of WeakReference class. It will return reference to the object if object is not yet removed from the memory.

4) Phantom References

The objects which are being referenced by phantom references are eligible for garbage collection. But, before

removing them from the memory, JVM puts them in a queue called ‘reference queue’ . They are put in a reference

queue after calling finalize() method on them. You can’t retrieve back the objects which are being phantom referenced. That means calling get() method on phantom reference always returns null.

Below example shows how to create Phantom References.

Page 22: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

22

class A { //A Class } public class MainClass { public static void main(String[] args) { A a = new A(); //Strong Reference //Creating ReferenceQueue ReferenceQueue<A> refQueue = new ReferenceQueue<A>(); //Creating Phantom Reference to A-type object to which 'a' is also pointing PhantomReference<A> phantomA = new PhantomReference<A>(a, refQueue); a = null; //Now, A-type object to which 'a' is pointing earlier is available for garbage collection. But, this object is kept in 'refQueue' before removing it from the memory. a = phantoma. get(); //it always returns null }

13. Q13. Suppose we have a circular reference (two objects that reference each other). Could such pair of objects become eligible for garbage collection and why?

Yes, a pair of objects with a circular reference can become eligible for garbage collection. This is because of how Java’s garbage collector handles circular references. It considers objects live not when they have any reference to them, but when they are reachable by navigating the object graph starting from some garbage collection root (a local variable of a live thread or a static field). If a pair of objects with a circular reference is not reachable from any root, it is considered eligible for garbage collection.

14. Q14. How are strings represented in memory?

A String instance in Java is an object with two fields: a char[] value field and an int hash field. The value field is an

array of chars representing the string itself, and the hash field contains the hashCode of a string which is initialized with

zero, calculated during the first hashCode() call and cached ever since. As a curious edge case, if a hashCode of a

string has a zero value, it has to be recalculated each time the hashCode() is called.

Important thing is that a String instance is immutable: you can’t get or modify the underlying char[] array. Another

feature of strings is that the static constant strings are loaded and cached in a string pool. If you have multiple

identical String objects in your source code, they are all represented by a single instance at runtime.

15. Q15. What is a StringBuilder and what are its use cases? What is the difference between appending a string to a StringBuilder and concatenating two strings with a + operator? How does StringBuilder differ from StringBuffer?

StringBuilder allows manipulating character sequences by appending, deleting and inserting characters and strings.

This is a mutable data structure, as opposed to the String class which is immutable.

When concatenating two String instances, a new object is created, and strings are copied. This could bring a huge

garbage collector overhead if we need to create or modify a string in a loop. StringBuilder allows handling string

manipulations much more efficiently.

StringBuffer is different from StringBuilder in that it is thread-safe. If you need to manipulate a string in a single

Page 23: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

23

thread, use StringBuilder instead.

Page 24: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

24

Memory Leaks

16. Memory Leak causes

1. Strings or substrings

2. Circular and Complex Bi-Directional References

3. Mutable Static Fields and Collections

4. Thread local variable

5. Static field holding object reference

6. Unclosed open streams

7. Unclosed connections

8. Bad hashcode

17. How does substring creates memory leak in Java

There is a potential for a memory leak, if you take a substring of a sizable string and not make a copy (usually via the String(String) CONSTRUCTOR).

Note that this has changed since Java 7u6. See http://bugs.sun.com/view_bug.do?bug_id=4513622.

The original assumptions around the String object implementing a flyweight pattern are no longer regarded as valid.

18. What is a thread local variable in Java?

Static fields are never garbage-collected!

For convenience alone, static fields and collections are often used to hold caches or share state across threads.

Mutable static fields need to be cleaned up explicitly.

This sort of careless programming means that static fields and collections have become the most common cause of memory leaks!

19. Static field holding object reference [esp final field]

class MemorableClass { static final ArrayList list = new ArrayList(100); }

20. Circular and Complex Bi-Directional References

Memory leaks due to overly complex and circular object structures

org.w3c.dom.Document doc = readXmlDocument(); org.w3c.dom.Node child = doc.getDocumentElement().getFirstChild(); doc.removeNode(child); doc = null;

21. What is a thread local variable in Java?

A thread-local variable is basically a member field in the Thread class.

In a multithreaded application, every thread instance has its own instance of such a variable. Therefore it can be very useful to bind a state to a thread. But this can be dangerous because thread-local variables will not be removed by the garbage collector as long as the thread itself is alive. As threads are often pooled and thus kept alive virtually forever, the object might never be removed by the garbage collector!

thread-local variable is very similar to a static variable. T.

Page 25: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

25

These kinds of memory leaks can be discovered with a heap dump. Just take a look at the ThreadLocalMap in the heap dump and follow the references

22. Unclosed) open streams ( file , network etc... )

try { BufferedReader br = new BufferedReader(new FileReader(inputFile)); ... ... } catch (Exception e) { e.printStacktrace(); }

23. Unclosed connections

try { Connection conn = ConnectionFactory.getConnection(); ... ... } catch (Exception e) { e.printStacktrace()}

24. HashSet with an incorrect hashCode() or equals, keep adding duplicates.

25. What best practices you follow with Monitor and Fix Resource Leaks

Always release database connections when querying is complete.

Try to use Finally block as often possible.

Release instances stored in Static Tables.

Baeldung

Garbage Collection

26. Which statement is true? A. Memory is reclaimed by calling Runtime.gc().

B. Objects are not collected if they are accessible from live threads.

C. An OutOfMemory error is only thrown if a single block of memory cannot be found that is large enough for a particular requirement.

D. Objects that have finalize() methods always have their finalize() methods called before the program ends.

Correct Answer: Option B

Explanation:

Option B is correct. If an object can be accessed from a live thread, it can't be garbage collected.

Option A is wrong. Runtime. gc() asks the garbage collector to run, but the garbage collector never makes any guarantees about when it will run or what unreachable objects it will free from memory.

Option C is wrong. The garbage collector runs immediately the system is out of memory before

an OutOfMemoryException is thrown by the JVM.

Option D is wrong. If this were the case then the garbage collector would actively hang onto objects until a program

Page 26: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

26

finishes - this goes against the purpose of the garbage collector.

27. At what point is the Bar object, created on line 6, eligible for garbage collection?

class Bar { }

class Test

{

Bar doBar()

{

Bar b = new Bar(); /* Line 6 */

return b; /* Line 7 */

}

public static void main (String args[])

{

Test t = new Test(); /* Line 11 */

Bar newBar = t.doBar(); /* Line 12 */

System.out.println("newBar");

newBar = new Bar(); /* Line 14 */

System.out.println("finishing"); /* Line 15 */

}

}

A. after line 1

B. after line 14

C. after line 7, when doBar() completes

D. after line 15, when main() completes

Correct Answer: Option B

Explanation:

Option B is correct. All references to the Bar object created on line 6 are destroyed when a new reference to a

new Bar object is assigned to the variable newBar on line 14. Therefore the Bar object, created on line 6, is eligible for garbage collection after line 14.

Option A is wrong. This actually protects the object from garbage collection.

Option C is wrong. Because the reference in the doBar() method is returned on line 7 and is stored in newBaron

line 12. This preserver the object created on line 6.

Option D is wrong. Not applicable because the object is eligible for garbage collection after line 14.

Page 27: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

27

28. When is the Demo object eligible for garbage collection?

class Test

{

private Demo d;

void start()

{

d = new Demo();

this.takeDemo(d); /* Line 7 */

} /* Line 8 */

void takeDemo(Demo demo)

{

demo = null;

demo = new Demo();

}

}

A. After line 7

B. After line 8

C. After the start() method completes

D. When the instance running this code is made eligible for garbage collection.

Correct Answer: Option D

Explanation:

Option D is correct. By a process of elimination.

Option A is wrong. The variable d is a member of the Test class and is never directly set to null.

Option B is wrong. A copy of the variable d is set to null and not the actual variable d.

Option C is wrong. The variable d exists outside the start() method (it is a class member). So, when

the start() method finishes the variable d still holds a reference.

29. After line 8 runs. how many objects are eligible for garbage collection?

public class X

{

Page 28: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

28

public static void main(String [] args)

{

X x = new X();

X x2 = m1(x); /* Line 6 */

X x4 = new X();

x2 = x4; /* Line 8 */

doComplexStuff();

}

static X m1(X mx)

{

mx = new X();

return mx;

}

}

A. 0

B. 1

C. 2

D. 3

Correct Answer: Option B

Explanation:

By the time line 8 has run, the only object without a reference is the one generated as a result of line 6. Remember

that "Java is pass by value," so the reference variable x is not affected by the m1() method.

Ref: http://www.javaworld. com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

To conclude everything in Java including primitive and objects are pass by value. In case of object value of reference is passed.

IndiaBIX

30. When is the Float object, created in line 3, eligible for garbage collection?

public Object m()

{

Object o = new Float(3.14F);

Object [] oa = new Object[l];

oa[0] = o; /* Line 5 */

o = null; /* Line 6 */

oa[0] = null; /* Line 7 */

return o; /* Line 8 */

Page 29: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

29

}

A. just after line 5

B. just after line 6

C. just after line 7

D. just after line 8

Correct Answer: Option C

Explanation:

Option A is wrong. This simply copies the object reference into the array.

Option B is wrong. The reference o is set to null, but, oa[0] still maintains the reference to the Float object.

Option C is correct. The thread of execution will then not have access to the object.

Garabage Collection rule says when, an object reference is nullyfy, then it is eligible for garbage collection.

Rule 1 : Nulling a Reference.

rule 2: Reassigning a Reference Variable

rule 3 : Isolating a Reference

31. Garbage Collection? A. Calling Runtime. gc() will cause eligible objects to be garbage collected.

B. The garbage collector uses a mark and sweep algorithm.

C. If an object can be accessed from a live thread, it can't be garbage collected.

D. If object 1 refers to object 2, then object 2 can't be garbage collected.

Correct Answer: Option C

Explanation:

This is a great way to think about when objects can be garbage collected.

Option A and B assume guarantees that the garbage collector never makes.

Option D is wrong because of the now famous islands of isolation scenario.

32. Memory quesiton? A. Memory is reclaimed by calling Runtime. gc().

B. Objects are not collected if they are accessible from live threads.

C. An OutOfMemory error is only thrown if a single block of memory cannot be found that is large enough for a particular requirement.

Page 30: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

30

33. What allows the programmer to destroy an object x? A. x.delete()

B. x.finalize()

C. Runtime. getRuntime().gc()

D. Only the garbage collection system can destroy an object.

Correct Answer: Option D

Explanation:

Option D is correct. When an object is no longer referenced, it may be reclaimed by the garbage collector. If an object declares a finalizer, the finalizer is executed before the object is reclaimed to give the object a last chance to clean up resources that would not otherwise be released. When a class is no longer needed, it may be unloaded.

Option A is wrong.

I found 4 delete() methods in all of the Java class structure. They are:

1. delete() - Method in class java. io.File : Deletes the file or directory denoted by this abstract pathname.

2. delete(int, int) - Method in class java. lang.StringBuffer : Removes the characters in a substring of this StringBuffer.

3. delete(int, int) - Method in interface javax.accessibility.AccessibleEditableText : Deletes the text between two indices

4. delete(int, int) - Method in class : javax.swing.text.JTextComponent.AccessibleJTextComponent; Deletes the text between two indices

None of these destroy the object to which they belong.

Option B is wrong.

I found 19 finalize() methods. The most interesting, from this questions point of view, was

the finalize() method in class java. lang.Object which is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. This method does not destroy the object to which it belongs.

Option C is wrong. But it is interesting. The Runtime class has many methods, two of which are:

1. getRuntime() - Returns the runtime object associated with the current Java application.

2. gc() - Runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects. Interesting as this is, it doesn't destroy the object.

3.

4.

D. Objects that have finalize() methods always have their finalize() methods called before the program ends.

Correct Answer: Option B

Explanation:

Option B is correct. If an object can be accessed from a live thread, it can't be garbage collected.

Page 31: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

31

Option A is wrong. Runtime. gc() asks the garbage collector to run, but the garbage collector never makes any guarantees about when it will run or what unreachable objects it will free from memory.

Option C is wrong. The garbage collector runs immediately the system is out of memory before

an OutOfMemoryException is thrown by the JVM.

Option D is wrong. If this were the case then the garbage collector would actively hang onto objects until a program finishes - this goes against the purpose of the garbage collector.

34. When is the Float object, created in line 3, eligible for garbage collection? public Object m() {

Object o = new Float(3.14F); Object [] oa = new Object[l]; oa[0] = o; /* Line 5 */ o = null; /* Line 6 */ oa[0] = null; /* Line 7 */ return o; /* Line 8 */ // The thread of execution will then not have access to the object }

a. just after line 5

b. just after line 6

c. just after line 7

d. just after line 8

Answer: Option C

Explanation:

Option A is wrong. This simply copies the object reference into the array.

Option B is wrong. The reference o is set to null, but, oa[0] still maintains the reference to the Float object.

Option C is correct. The thread of execution will then not have access to the object.

35. When is the B object, created in line 3, eligible for garbage collection? void start() { A a = new A(); B b = new B(); a. s(b);

b = null; /* Line 5 */ a = null; /* Line 6 */ System.out.println("start completed"); /* Line 7 */ }

A. after line

B. after line

C. after line

D. There is no way to be absolutely certain.

Correct Answer: Option D

Page 32: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

32

36. after line 11 runs, how many objects are eligible for garbage collection? Isolated objects class X2 { public X2 x; public static void main(String [] args) {

X2 x2 = new X2(); /* Line 6 */ X2 x3 = new X2(); /* Line 7 */ x2.x = x3; x3.x = x2;

x2 = new X2(); x3 = x2; /* Line 11 */ doComplexStuff(); } }

A. 0

B. 1

C. 2

D. 3

Correct Answer: Option C

Explanation:

This is an example of the islands of isolated objects. By the time line 11 has run, the objects instantiated in lines 6 and 7 are referring to each other, but no live thread can reach either of them.

37. The following code creates one array and one string object. How many references to those objects exist after the code executes? Is either object eligible for garbage collection?

... String[] students = new String[10]; String studentName = "Peter Smith"; students[0] = studentName; studentName = null; ...

Answer: There is one reference to the students array and that array has one reference to the string Peter Smith.

Neither object is eligible for garbage collection. The array students is not eligible for garbage collection because it

has one reference to the object studentName even though that object has been assigned the value null. The

object studentName is not eligible either because students[0] still refers to it.

38. How does a program destroy an object that it creates?

Answer: A program does not explicitly destroy objects. A program can set all references to an object to null so that it

becomes eligible for garbage collection. But the program does not actually destroy objects.

SIB – Static Initialization Block, Static Variables And Static Methods

pramodbablad May 8, 2014 23

Page 33: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

33

Static variables, Static Initialization Block and Static Methods – these all are static components or static members of a class.

These static members are stored inside the Class Memory.

To access static members, you need not to create objects.

Directly you can access them with class name.

Static Initialization Block is used to initialize only static variables. It is a block without a name. It contains set of statements enclosed within { }. The syntax of SIB looks like this,

static { //Set Of Statements }

Consider the following program.

class StaticComponents

{ static int staticVariable; static { System.out.println("StaticComponents SIB"); staticVariable = 10; } static void staticMethod() { System.out.println("From StaticMethod"); System.out.println(staticVariable); } } public class MainClass { static { System.out.println("MainClass SIB"); } public static void main(String[] args) { //Static Members directly accessed with Class Name StaticComponents.staticVariable = 20; StaticComponents.staticMethod(); } }

Let us discuss execution of above program step by step.

Step 1:

5. When you trigger >java MainClass, java command divides allocated memory into two parts – Stack and Heap.

6. First, java command enters stack memory for execution.

7. First, it checks whether MainClass is loaded into heap memory or not. If it is not loaded, loading operation of MainClass starts.

8. Randomly some memory space is allocated to MainClass. It is called Class memory. All static members are loaded into this class

memory. There is only one satic member in MainClass – main() method. It is loaded into class memory of MainClass.

Step 2:

9. After loading all static members, SIB – Static initialization Blocks are executed.

Page 34: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

34

10. Remember, SIBs are not stored in the heap memory. They just come to stack, execute their tasks and leaves the memory. So, after loading main() method, SIB of MainClass enters stack for execution. There is only one statement (Line

22) in SIb. it is executed. It prints “MainClass SIB” on console. After executing this statement, SIB leaves the stack memory.

Step 3:

11. Now, java command calls main() method for execution. main() method enters the stack. First statement (Line 28) is executed first. First, It checks whether class StaticComponents is loaded into memory. If it is not loaded, loading operation of StaticComponents takes place. Randomly, some memory is allocated to Class StaticComponents, then all static members of StaticComponents – ‘staticVariable’ and ‘staticMethod()’ are loaded into that class memory. ‘staticVariable’ is a global variable. So, first it is initialized with default value i.e 0.

Step 4 :

12. After loading all static members of StaticComponents, SIB blocks are executed. So, SIB of class StaticComponents enters the stack for execution. First Statement (Line 7) is executed. It prints “StaticComponents SIB” on the console. In the second statement, value 10 is assigned to ‘staticVariable’. There are no other statements left for execution, so it leaves stack memory.

Step 5 :

13. Now control comes back to main() method. The remaining part of first statement i.e value 20 is assigned to ‘staticVariable’ of class StaticComponents, is executed. In the second statement (Line 29), it calls staticMethod() of class StaticComponents for execution.

Step 6:

14. staticMethod() of StaticComponents enters stack for execution. First statement (Line 13) is executed first. It prints “From staticMethod” on the console. In the second statement (Line 14), it prints the value of staticVariable i.e 20 on the console. There are no statements left. so, it leaves the stack.

Step 7:

15. Again, control comes back to main() method. There are no other statements left in main() method. so, it also leaves stack. java command also leaves the stack.

Diagramatic representation of memory allocation of above program looks like this.

Output :

Page 35: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

35

Main Class SIB

StaticComponents SIB

From StaticMethod

Non-Static Members And Their Memory Management In Java

pramodbablad May 9, 2014 10

A class is like a blue print of a house. With this blueprint, you can build any number of houses. Each house build with this blueprint is an object or an instance of that blue print.

Non-Static variables and Non-Static methods are non-static components of a class. These are also called instance components of a class. Non-static components are stored inside the object memory. Each object will have their own copy of non-static components. But, static components are common to all objects of that class.

Let’s have a look at this example.

class A

{ int nonStaticVariable; static int staticVariable; static void staticMethod() { System.out.println(staticVariable); // System.out.println(nonStaticVariable); } void nonStaticMethod() { System.out.println(staticVariable); System.out.println(nonStaticVariable); } } class MainClass { public static void main(String[] args) { a. staticVariable = 10; // a. nonStaticVariable = 10; a. staticMethod(); // a. nonStaticMethod(); A a1 = new A(); A a2 = new A(); System.out.println(a1.nonStaticVariable); System.out.println(a1.staticVariable); a1.nonStaticMethod(); a1.staticMethod(); System.out.println(a2.staticVariable); a1.staticVariable = 20; System.out.println(a2.staticVariable); } }

Let’s discuss memory allocation of above example step by step.

Page 36: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

36

Step 1 :

When you trigger >java MainClass, java command divides allocated memory into two parts – stack and heap. First java command enters stack for execution. First it loads class MainClass into heap memory. Randomly some memory is allocated to MainClass. All static members are loaded into this class memory. There is only one static member in MainClass i.e main() method. It is loaded into class memory. After loading static members, SIBs are executed. But there is no SIBs in MainClass. So, directly java command calls main() method for execution.

Step 2 :

main() method enters stack for execution. First statement (Line 23) refers to class a. First it checks whether class A is loaded into heap memory or not. If it is not loaded, it loads class A into heap memory. Randomly some memory is allocated to class a. All static members of class A , ‘staticVariable’ and ‘staticMethod()’ , are loaded into this memory. ‘staticVariable’ is first initialized with default value 0. No SIBs in Class a. So, after loading static members, main() method assigns value 10 to ‘staticVariable’ of class a. Second statement (Line 24) of main() method is commented. Because, you can’t refer a non-static members through a class name. Because, non-static members are stored inside the object memory. You have to refer them through objects only.

Step 3 :

In Line 25, it calls staticMethod() of class a. staticMethod() comes to stack for execution. First statement(Line 8) prints value of ‘staticVariable’ i. e 10 on the console.

Second statement(Line 9) is commented. Because, directly you can’t use non-static member inside a static method. Because, non-static members are stored inside the object memory. You have to create objects to use them. You have to refer them through objects only.

No statements left in staticMethod(). So, it leaves the stack memory.

Step 4 :

Control comes back to main() method. The next statement (Line 26) is also commented. Because, You can’t refer non-static member through a class name. In the next statement (Line 28), an object of class A type is created. Randomly, some memory is allocated to object. All non-static members, ‘nonStaticVariable’ and ‘nonStaticMethod()’, of class A are loaded into this object memory. ‘nonStaticVariable’ is a global variable, so it is first initialized with default value 0. A reference variable of type class A ‘a1’ is created in main() method. It points to this newly created object.

In the same manner, object ‘a2’ is also created (Line 29). In the next statement (Line 31), value of ‘nonStaticVariable’ of ‘a1’ i.e 0 is printed. In the next statement (Line 32), value of ‘staticVariable’ of class A i.e 10 is printed.

You can refer a static member of a class through object of that class like in Line 32. Whenever you refer a static member through a object, compiller replaces object name with its class name like a1.staticVariable is treated as a. staticVariable by the compiler.

In the next statement (Line 33), it calls ‘nonStaticMethod()’ of a1.

Step 5 :

‘nonStaticMethod()’ of a1 comes to the stack for execution. First statement (Line 14) prints value of ‘staticVariable’ of class A i.e 10 on the console. Second statement (Line 15) prints the value of ‘nonStaticVariable’ of a1 i.e 0. There are no other statements left in ‘nonStaticMethod()’ , so it leaves the stack.

Step 6 :

Control comes back to Line 34 of main() method. It calls staticMethod() of class a. ‘staticMethod()’ enters the stack for execution. First statment (Line 8) prints value of ‘staticVariable’ i.e 10 on the console. It leaves the memory after executing this statement.

Step 7 :

Page 37: Sat 1/6/2018 JAVA (JVM) MEMORY MODEL – MEMORY MANAGEMENT IN … · 2019-02-11 · Java (JVM) Memory Model – Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS

Sat 1/6/2018

37

Control comes back to the main() method. Line 36 prints value of ‘staticVariable’ i.e 10 on the console through object a2. In the next statement it changes value of ‘staticVariable’ to 20 through a1. In the next statement, again it prints the value of ‘staticVariable’ through a2. This time 20 is printed on the console.

This means changes made to static components through one object is reflected in another object also. Because, the same copy of static components is available to all the objects of that class.

As all statements are executed, first main() method then java command leaves the stack memory.

Diagramatic representation of memory allocation of above program looks like this,

Output :

10

0

10

10

0

10

10

2

http://javaconceptoftheday.com/non-static-members-in-java/


Recommended