Sat 1/6/2018 JAVA (JVM) MEMORY MODEL MEMORY MANAGEMENT IN JAVA... 3 WHERE STORAGE LIVES... 3

Size: px
Start display at page:

Download "Sat 1/6/2018 JAVA (JVM) MEMORY MODEL MEMORY MANAGEMENT IN JAVA... 3 WHERE STORAGE LIVES... 3"

Transcription

1 JAVA (JVM) MEMORY MODEL MEMORY MANAGEMENT IN JAVA 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 INTRODUCTION Q1. What does the statement memory is managed in Java mean? Q2. What is Garbage Collection and what are its advantages? Q3. Are there any disadvantages of Garbage Collection? Q4. What is the meaning of the term stop-the-world? Q5. What are stack and heap? What is stored in each of these memory structures, and how are they interrelated? Q6. What is generational garbage collection and what makes it a popular garbage collection approach? Q7. Describe in detail how generational garbage collection works Q8. When does an object become eligible for garbage collection? Describe how the GC collects an eligible object? Q9. How do you trigger garbage collection from Java code? Q10. What happens when there is not enough heap space to accommodate storage of new objects? Q11. Is it possible to «resurrect» an object that became eligible for garbage collection? In Java, no variable can ever hold an object. A variable can only hold a reference to an object TYPES OF REFERENCES IN JAVA : STRONG, SOFT, WEAK AND PHANTOM Strong Reference Soft reference Weak reference Phantom reference ) STRONG REFERENCES ) SOFT REFERENCES ) WEAK REFERENCES ) PHANTOM REFERENCES 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? Q14. How are strings represented in memory? 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? MEMORY LEAKS Memory Leak causes How does substring creates memory leak in Java What is a thread local variable in Java? Static field holding object reference [esp final field] Circular and Complex Bi-Directional References What is a thread local variable in Java?... 24

2 22. Unclosed) open streams ( file, network etc... ) Unclosed connections HashSet with an incorrect hashcode() or equals, keep adding duplicates What best practices you follow with Monitor and Fix Resource Leaks GARBAGE COLLECTION Which statement is true? At what point is the Bar object, created on line 6, eligible for garbage collection? When is the Demo object eligible for garbage collection? After line 8 runs. how many objects are eligible for garbage collection? When is the Float object, created in line 3, eligible for garbage collection? GARABAGE COLLECTION RULE SAYS WHEN, AN OBJECT REFERENCE IS NULLYFY, THEN IT IS ELIGIBLE FOR GARBAGE COLLECTION Garbage Collection? Memory quesiton? What allows the programmer to destroy an object x? When is the Float object, created in line 3, eligible for garbage collection? When is the B object, created in line 3, eligible for garbage collection? after line 11 runs, how many objects are eligible for garbage collection? Isolated objects 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? How does a program destroy an object that it creates? SIB STATIC INITIALIZATION BLOCK, STATIC VARIABLES AND STATIC METHODS Diagramatic representation of memory allocation of above program looks like this MAIN CLASS SIB STATICCOMPONENTS SIB FROM STATICMETHOD NON-STATIC MEMBERS AND THEIR MEMORY MANAGEMENT IN JAVA

3 Java (JVM) Memory Model Memory Management in Java SEPTEMBER 18, 2017 BY PANKAJ 87 COMMENTS Where storage lives 3 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

4 boolean Boolean char 16-bit Unicode 0 byte 8-bit -1+1Byte short 16-bit int 32-bit Integer long 64-bit float 32-bit IEEE7IEEE7Float double 64-bit IEEE7IEEE7Double void Void Unicode Character Short Long 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. 4

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. 5

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 6

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. 7

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. 8

9 ps -eaf grep Java2Demo.jar :48PM ttys000 0:21.66 /usr/bin/java - Xmx120m -Xms30m -Xmn10m -XX:PermSize=20m -XX:MaxPermSize=20m - XX:+UseG1GC -jar Java2Demo.jar :48PM ttys002 0:00.00 grep Java2Demo.jar So the process id for my java application is Now we can run jstat command as shown below. pankaj@pankaj:~$ jstat -gc S0C S1C S0U S1U EC EU OC OU PC PU YGC YGCT FGC FGCT GCT 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. 9

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 10 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.

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? 11 The stack is a part of memory that contains information about nested method calls down to the current position in the

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. 12 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

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. 13

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, std2, std3; // Declare four variables of // 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 14 // it in the variable std1.

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)" 15

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 StringBuilder sb = new StringBuilder(); 2 SoftReference<StringBuilder> sbref = new SoftReference<>(sb); 3 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. 16

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, 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 17 a = null; garbage collection. //Now, object to which 'a' is pointing earlier is eligible for 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.

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. 18 a = softa. get(); softly referenced //You can retrieve back the object which has been 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

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. 19

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(); weakly referenced. Look at the below picture for more clear understanding. //You can retrieve back the object which has been 20

21 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.

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 22

23 thread, use StringBuilder instead. 23

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 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. 24

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 25

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

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 27

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: com/javaworld/javaqa/ /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 */ 28

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. 29

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 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. 30

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 31

32 36. after line 11 runs, how many objects are eligible for garbage collection? Isolated objects class X2 public X2 x; A. 0 B. 1 C. 2 D. 3 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(); 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,

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); 33 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.

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 : 34

35 Main Class SIB StaticComponents SIB From StaticMethod Non-Static Members And Their Memory Management In Java pramodbablad May 9, 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); 35 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.

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 : 36

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 :

JVM Memory Model and GC

JVM Memory Model and GC JVM Memory Model and GC Developer Community Support Fairoz Matte Principle Member Of Technical Staff Java Platform Sustaining Engineering, Copyright 2015, Oracle and/or its affiliates. All rights reserved.

More information

Java Performance Tuning

Java Performance Tuning 443 North Clark St, Suite 350 Chicago, IL 60654 Phone: (312) 229-1727 Java Performance Tuning This white paper presents the basics of Java Performance Tuning and its preferred values for large deployments

More information

Fundamentals of GC Tuning. Charlie Hunt JVM & Performance Junkie

Fundamentals of GC Tuning. Charlie Hunt JVM & Performance Junkie Fundamentals of GC Tuning Charlie Hunt JVM & Performance Junkie Who is this guy? Charlie Hunt Currently leading a variety of HotSpot JVM projects at Oracle Held various performance architect roles at Oracle,

More information

Attila Szegedi, Software

Attila Szegedi, Software Attila Szegedi, Software Engineer @asz Everything I ever learned about JVM performance tuning @twitter Everything More than I ever wanted to learned about JVM performance tuning @twitter Memory tuning

More information

Java Performance Tuning From A Garbage Collection Perspective. Nagendra Nagarajayya MDE

Java Performance Tuning From A Garbage Collection Perspective. Nagendra Nagarajayya MDE Java Performance Tuning From A Garbage Collection Perspective Nagendra Nagarajayya MDE Agenda Introduction To Garbage Collection Performance Problems Due To Garbage Collection Performance Tuning Manual

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Java & Coherence Simon Cook - Sales Consultant, FMW for Financial Services

Java & Coherence Simon Cook - Sales Consultant, FMW for Financial Services Java & Coherence Simon Cook - Sales Consultant, FMW for Financial Services with help from Adrian Nakon - CMC Markets & Andrew Wilson - RBS 1 Coherence Special Interest Group Meeting 1 st March 2012 Presentation

More information

2011 Oracle Corporation and Affiliates. Do not re-distribute!

2011 Oracle Corporation and Affiliates. Do not re-distribute! How to Write Low Latency Java Applications Charlie Hunt Java HotSpot VM Performance Lead Engineer Who is this guy? Charlie Hunt Lead JVM Performance Engineer at Oracle 12+ years of

More information

Exploiting the Behavior of Generational Garbage Collector

Exploiting the Behavior of Generational Garbage Collector Exploiting the Behavior of Generational Garbage Collector I. Introduction Zhe Xu, Jia Zhao Garbage collection is a form of automatic memory management. The garbage collector, attempts to reclaim garbage,

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

CS 241 Honors Memory

CS 241 Honors Memory CS 241 Honors Memory Ben Kurtovic Atul Sandur Bhuvan Venkatesh Brian Zhou Kevin Hong University of Illinois Urbana Champaign February 20, 2018 CS 241 Course Staff (UIUC) Memory February 20, 2018 1 / 35

More information

MEMORY MANAGEMENT HEAP, STACK AND GARBAGE COLLECTION

MEMORY MANAGEMENT HEAP, STACK AND GARBAGE COLLECTION MEMORY MANAGEMENT HEAP, STACK AND GARBAGE COLLECTION 2 1. What is the Heap Size: 2 2. What is Garbage Collection: 3 3. How are Java objects stored in memory? 3 4. What is the difference between stack and

More information

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2 CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,

More information

Java Memory Management. Märt Bakhoff Java Fundamentals

Java Memory Management. Märt Bakhoff Java Fundamentals Java Memory Management Märt Bakhoff Java Fundamentals 0..206 Agenda JVM memory Reference objects Monitoring Garbage collectors ParallelGC GGC 2/44 JVM memory Heap (user objects) Non-heap Stack (per thread:

More information

Lecture Notes on Memory Layout

Lecture Notes on Memory Layout Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,

More information

G1 Garbage Collector Details and Tuning. Simone Bordet

G1 Garbage Collector Details and Tuning. Simone Bordet G1 Garbage Collector Details and Tuning Who Am I - @simonebordet Lead Architect at Intalio/Webtide Jetty's HTTP/2, SPDY and HTTP client maintainer Open Source Contributor Jetty, CometD, MX4J, Foxtrot,

More information

The Fundamentals of JVM Tuning

The Fundamentals of JVM Tuning The Fundamentals of JVM Tuning Charlie Hunt Architect, Performance Engineering Salesforce.com sfdc_ppt_corp_template_01_01_2012.ppt In a Nutshell What you need to know about a modern JVM to be effective

More information

Garbage collection. The Old Way. Manual labor. JVM and other platforms. By: Timo Jantunen

Garbage collection. The Old Way. Manual labor. JVM and other platforms. By: Timo Jantunen Garbage collection By: Timo Jantunen JVM and other platforms In computer science, garbage collection (gc) can mean few different things depending on context and definition. In this post, it means "freeing

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level

More information

Contents. Created by: Raúl Castillo

Contents. Created by: Raúl Castillo Contents 1. Introduction... 3 2. he garbage collector... 3 3. Some concepts regarding to garbage collection... 4 4. ypes of references in Java... 7 5. Heap based on generations... 9 6. Garbage collection

More information

20 Most Important Java Programming Interview Questions. Powered by

20 Most Important Java Programming Interview Questions. Powered by 20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by

More information

JVM Troubleshooting MOOC: Troubleshooting Memory Issues in Java Applications

JVM Troubleshooting MOOC: Troubleshooting Memory Issues in Java Applications JVM Troubleshooting MOOC: Troubleshooting Memory Issues in Java Applications Poonam Parhar JVM Sustaining Engineer Oracle Lesson 1 HotSpot JVM Memory Management Poonam Parhar JVM Sustaining Engineer Oracle

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 - Spring 2013 1 Memory Attributes! Memory to store data in programming languages has the following lifecycle

More information

Agenda. CSE P 501 Compilers. Java Implementation Overview. JVM Architecture. JVM Runtime Data Areas (1) JVM Data Types. CSE P 501 Su04 T-1

Agenda. CSE P 501 Compilers. Java Implementation Overview. JVM Architecture. JVM Runtime Data Areas (1) JVM Data Types. CSE P 501 Su04 T-1 Agenda CSE P 501 Compilers Java Implementation JVMs, JITs &c Hal Perkins Summer 2004 Java virtual machine architecture.class files Class loading Execution engines Interpreters & JITs various strategies

More information

Structure of Programming Languages Lecture 10

Structure of Programming Languages Lecture 10 Structure of Programming Languages Lecture 10 CS 6636 4536 Spring 2017 CS 6636 4536 Lecture 10: Classes... 1/23 Spring 2017 1 / 23 Outline 1 1. Types Type Coercion and Conversion Type Classes, Generics,

More information

Debugging Your Production JVM TM Machine

Debugging Your Production JVM TM Machine Debugging Your Production JVM TM Machine Ken Sipe Perficient (PRFT) kensipe@gmail.com @kensipe Abstract > Learn the tools and techniques used to monitor, trace and debugging running Java applications.

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 Spring 2017 1 Memory Attributes Memory to store data in programming languages has the following lifecycle

More information

Lecture 13: Garbage Collection

Lecture 13: Garbage Collection Lecture 13: Garbage Collection COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer/Mikkel Kringelbach 1 Garbage Collection Every modern programming language allows programmers

More information

Garbage Collection. Hwansoo Han

Garbage Collection. Hwansoo Han Garbage Collection Hwansoo Han Heap Memory Garbage collection Automatically reclaim the space that the running program can never access again Performed by the runtime system Two parts of a garbage collector

More information

Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java)

Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java) COMP 412 FALL 2017 Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java) Copyright 2017, Keith D. Cooper & Zoran Budimlić, all rights reserved. Students enrolled in Comp 412 at Rice

More information

1. Mark-and-Sweep Garbage Collection

1. Mark-and-Sweep Garbage Collection Due: Tuesday, April 21, 2015. 11:59pm (no extensions). What to submit: A tar ball containing the files: Slide.java, slide.png or slide.pdf with your slide, benchmark.template, and any file(s) containing

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

CPS221 Lecture: Threads

CPS221 Lecture: Threads Objectives CPS221 Lecture: Threads 1. To introduce threads in the context of processes 2. To introduce UML Activity Diagrams last revised 9/5/12 Materials: 1. Diagram showing state of memory for a process

More information

Algorithms for Dynamic Memory Management (236780) Lecture 4. Lecturer: Erez Petrank

Algorithms for Dynamic Memory Management (236780) Lecture 4. Lecturer: Erez Petrank Algorithms for Dynamic Memory Management (236780) Lecture 4 Lecturer: Erez Petrank!1 March 24, 2014 Topics last week The Copying Garbage Collector algorithm: Basics Cheney s collector Additional issues:

More information

OOSD. Introduction to JAVA. Giuseppe Lipari Scuola Superiore Sant Anna Pisa. September 12, 2011

OOSD. Introduction to JAVA. Giuseppe Lipari  Scuola Superiore Sant Anna Pisa. September 12, 2011 OOSD Introduction to JAVA Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 12, 2011 G. Lipari (Scuola Superiore Sant Anna) OOSD September 12, 2011 1 / 55 Outline

More information

The G1 GC in JDK 9. Erik Duveblad Senior Member of Technical Staf Oracle JVM GC Team October, 2017

The G1 GC in JDK 9. Erik Duveblad Senior Member of Technical Staf Oracle JVM GC Team October, 2017 The G1 GC in JDK 9 Erik Duveblad Senior Member of Technical Staf racle JVM GC Team ctober, 2017 Copyright 2017, racle and/or its affiliates. All rights reserved. 3 Safe Harbor Statement The following is

More information

Runtime. The optimized program is ready to run What sorts of facilities are available at runtime

Runtime. The optimized program is ready to run What sorts of facilities are available at runtime Runtime The optimized program is ready to run What sorts of facilities are available at runtime Compiler Passes Analysis of input program (front-end) character stream Lexical Analysis token stream Syntactic

More information

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012) COE318 Lecture Notes: Week 3 1 of 8 COE318 Lecture Notes Week 3 (Week of Sept 17, 2012) Announcements Quiz (5% of total mark) on Wednesday, September 26, 2012. Covers weeks 1 3. This includes both the

More information

Do Your GC Logs Speak To You

Do Your GC Logs Speak To You Do Your GC Logs Speak To You Visualizing CMS, the (mostly) Concurrent Collector Copyright 2012 Kodewerk Ltd. All rights reserved About Me Consultant (www.kodewerk.com) performance tuning and training seminar

More information

Garbage Collection. Steven R. Bagley

Garbage Collection. Steven R. Bagley Garbage Collection Steven R. Bagley Reference Counting Counts number of pointers to an Object deleted when the count hits zero Eager deleted as soon as it is finished with Problem: Circular references

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

High-Level Language VMs

High-Level Language VMs High-Level Language VMs Outline Motivation What is the need for HLL VMs? How are these different from System or Process VMs? Approach to HLL VMs Evolutionary history Pascal P-code Object oriented HLL VMs

More information

Run-Time Environments/Garbage Collection

Run-Time Environments/Garbage Collection Run-Time Environments/Garbage Collection Department of Computer Science, Faculty of ICT January 5, 2014 Introduction Compilers need to be aware of the run-time environment in which their compiled programs

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC330 Fall 2018 1 Memory Attributes Memory to store data in programming languages has the following lifecycle

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information

Garbage Collection. Akim D le, Etienne Renault, Roland Levillain. May 15, CCMP2 Garbage Collection May 15, / 35

Garbage Collection. Akim D le, Etienne Renault, Roland Levillain. May 15, CCMP2 Garbage Collection May 15, / 35 Garbage Collection Akim Demaille, Etienne Renault, Roland Levillain May 15, 2017 CCMP2 Garbage Collection May 15, 2017 1 / 35 Table of contents 1 Motivations and Definitions 2 Reference Counting Garbage

More information

JBoss Performance Tuning. Bill Meyer JBoss Sr. Solutions Architect

JBoss Performance Tuning. Bill Meyer JBoss Sr. Solutions Architect JBoss Performance Tuning Bill Meyer JBoss Sr. Solutions Architect bill@redhat.com JVM Memory Tuning JVM Heap Total JVM Heap Major Collection Young Generation Minor Collection Old Generation Eden Survivor

More information

Memory Management: The Details

Memory Management: The Details Lecture 10 Memory Management: The Details Sizing Up Memory Primitive Data Types Complex Data Types byte: char: short: basic value (8 bits) 1 byte 2 bytes Pointer: platform dependent 4 bytes on 32 bit machine

More information

Heap Management. Heap Allocation

Heap Management. Heap Allocation Heap Management Heap Allocation A very flexible storage allocation mechanism is heap allocation. Any number of data objects can be allocated and freed in a memory pool, called a heap. Heap allocation is

More information

VARIABLES AND TYPES CITS1001

VARIABLES AND TYPES CITS1001 VARIABLES AND TYPES CITS1001 Scope of this lecture Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Primitive types Every piece of data

More information

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.! True object-oriented programming: Dynamic Objects Reference Variables D0010E Object-Oriented Programming and Design Lecture 3 Static Object-Oriented Programming UML" knows-about Eckel: 30-31, 41-46, 107-111,

More information

Inside the Garbage Collector

Inside the Garbage Collector Inside the Garbage Collector Agenda Applications and Resources The Managed Heap Mark and Compact Generations Non-Memory Resources Finalization Hindering the GC Helping the GC 2 Applications and Resources

More information

OOSD. Introduction to JAVA. Giuseppe Lipari Scuola Superiore Sant Anna Pisa. September 29, 2010

OOSD. Introduction to JAVA. Giuseppe Lipari   Scuola Superiore Sant Anna Pisa. September 29, 2010 OOSD Introduction to JAVA Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 29, 2010 G. Lipari (Scuola Superiore Sant Anna) OOSD September 29, 2010 1 / 55 Outline

More information

Project. there are a couple of 3 person teams. a new drop with new type checking is coming. regroup or see me or forever hold your peace

Project. there are a couple of 3 person teams. a new drop with new type checking is coming. regroup or see me or forever hold your peace Project there are a couple of 3 person teams regroup or see me or forever hold your peace a new drop with new type checking is coming using it is optional 1 Compiler Architecture source code Now we jump

More information

Running class Timing on Java HotSpot VM, 1

Running class Timing on Java HotSpot VM, 1 Compiler construction 2009 Lecture 3. A first look at optimization: Peephole optimization. A simple example A Java class public class A { public static int f (int x) { int r = 3; int s = r + 5; return

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1 CSE P 501 Compilers Java Implementation JVMs, JITs &c Hal Perkins Winter 2008 3/11/2008 2002-08 Hal Perkins & UW CSE V-1 Agenda Java virtual machine architecture.class files Class loading Execution engines

More information

Managed runtimes & garbage collection. CSE 6341 Some slides by Kathryn McKinley

Managed runtimes & garbage collection. CSE 6341 Some slides by Kathryn McKinley Managed runtimes & garbage collection CSE 6341 Some slides by Kathryn McKinley 1 Managed runtimes Advantages? Disadvantages? 2 Managed runtimes Advantages? Reliability Security Portability Performance?

More information

Java Without the Jitter

Java Without the Jitter TECHNOLOGY WHITE PAPER Achieving Ultra-Low Latency Table of Contents Executive Summary... 3 Introduction... 4 Why Java Pauses Can t Be Tuned Away.... 5 Modern Servers Have Huge Capacities Why Hasn t Latency

More information

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2 CPSC 213 Introduction to Computer Systems Winter Session 2017, Term 2 Unit 1c Jan 24, 26, 29, 31, and Feb 2 Instance Variables and Dynamic Allocation Overview Reading Companion: Reference 2.4.4-5 Textbook:

More information

Compiler Construction D7011E

Compiler Construction D7011E Compiler Construction D7011E Lecture 14: Memory Management Viktor Leijon Slides largely by Johan Nordlander with material generously provided by Mark P. Jones. 1 First: Run-time Systems 2 The Final Component:

More information

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management

More information

Managed runtimes & garbage collection

Managed runtimes & garbage collection Managed runtimes Advantages? Managed runtimes & garbage collection CSE 631 Some slides by Kathryn McKinley Disadvantages? 1 2 Managed runtimes Portability (& performance) Advantages? Reliability Security

More information

Lesson 2 Dissecting Memory Problems

Lesson 2 Dissecting Memory Problems Lesson 2 Dissecting Memory Problems Poonam Parhar JVM Sustaining Engineer Oracle Agenda 1. Symptoms of Memory Problems 2. Causes of Memory Problems 3. OutOfMemoryError messages 3 Lesson 2-1 Symptoms of

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Certified Core Java Developer VS-1036

Certified Core Java Developer VS-1036 VS-1036 1. LANGUAGE FUNDAMENTALS The Java language's programming paradigm is implementation and improvement of Object Oriented Programming (OOP) concepts. The Java language has its own rules, syntax, structure

More information

Programming Language Implementation

Programming Language Implementation A Practical Introduction to Programming Language Implementation 2014: Week 10 Garbage Collection College of Information Science and Engineering Ritsumeikan University 1 review of last week s topics dynamic

More information

Automatic Garbage Collection

Automatic Garbage Collection Automatic Garbage Collection Announcements: PS6 due Monday 12/6 at 11:59PM Final exam on Thursday 12/16 o PS6 tournament and review session that week Garbage In OCaml programs (and in most other programming

More information

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

Habanero Extreme Scale Software Research Project

Habanero Extreme Scale Software Research Project Habanero Extreme Scale Software Research Project Comp215: Garbage Collection Zoran Budimlić (Rice University) Adapted from Keith Cooper s 2014 lecture in COMP 215. Garbage Collection In Beverly Hills...

More information

CS577 Modern Language Processors. Spring 2018 Lecture Garbage Collection

CS577 Modern Language Processors. Spring 2018 Lecture Garbage Collection CS577 Modern Language Processors Spring 2018 Lecture Garbage Collection 1 BASIC GARBAGE COLLECTION Garbage Collection (GC) is the automatic reclamation of heap records that will never again be accessed

More information

the gamedesigninitiative at cornell university Lecture 9 Memory Management

the gamedesigninitiative at cornell university Lecture 9 Memory Management Lecture 9 Gaming Memory Constraints Redux Wii-U Playstation 4 2GB of RAM 1GB dedicated to OS Shared with GPGPU 8GB of RAM Shared GPU, 8-core CPU OS footprint unknown 2 Two Main Concerns with Memory Getting

More information

Contents. 8-1 Copyright (c) N. Afshartous

Contents. 8-1 Copyright (c) N. Afshartous Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10 Introduction to Object-Oriented

More information

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection Deallocation Mechanisms User-controlled Deallocation Allocating heap space is fairly easy. But how do we deallocate heap memory no longer in use? Sometimes we may never need to deallocate! If heaps objects

More information

CS220 Database Systems. File Organization

CS220 Database Systems. File Organization CS220 Database Systems File Organization Slides from G. Kollios Boston University and UC Berkeley 1.1 Context Database app Query Optimization and Execution Relational Operators Access Methods Buffer Management

More information

Programming in the Large II: Objects and Classes (Part 1)

Programming in the Large II: Objects and Classes (Part 1) Programming in the Large II: Objects and Classes (Part 1) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen

More information

Motivation was to facilitate development of systems software, especially OS development.

Motivation was to facilitate development of systems software, especially OS development. A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.

More information

Automatic Memory Management

Automatic Memory Management Automatic Memory Management Why Automatic Memory Management? Storage management is still a hard problem in modern programming Why Automatic Memory Management? Storage management is still a hard problem

More information

Java Application Performance Tuning for AMD EPYC Processors

Java Application Performance Tuning for AMD EPYC Processors Java Application Performance Tuning for AMD EPYC Processors Publication # 56245 Revision: 0.70 Issue Date: January 2018 Advanced Micro Devices 2018 Advanced Micro Devices, Inc. All rights reserved. The

More information

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1) Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types

More information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Lecture 3. Lecture

Lecture 3. Lecture True Object-Oriented programming: Dynamic Objects Static Object-Oriented Programming Reference Variables Eckel: 30-31, 41-46, 107-111, 114-115 Riley: 5.1, 5.2 D0010E Object-Oriented Programming and Design

More information

Compiler construction 2009

Compiler construction 2009 Compiler construction 2009 Lecture 3 JVM and optimization. A first look at optimization: Peephole optimization. A simple example A Java class public class A { public static int f (int x) { int r = 3; int

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Soda Machine Laboratory

Soda Machine Laboratory Soda Machine Laboratory Introduction This laboratory is intended to give you experience working with multiple queue structures in a familiar real-world setting. The given application models a soda machine

More information

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

CS 326: Operating Systems. Process Execution. Lecture 5

CS 326: Operating Systems. Process Execution. Lecture 5 CS 326: Operating Systems Process Execution Lecture 5 Today s Schedule Process Creation Threads Limited Direct Execution Basic Scheduling 2/5/18 CS 326: Operating Systems 2 Today s Schedule Process Creation

More information

Motivation was to facilitate development of systems software, especially OS development.

Motivation was to facilitate development of systems software, especially OS development. A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

COMP 250 Winter 2011 Reading: Java background January 5, 2011

COMP 250 Winter 2011 Reading: Java background January 5, 2011 Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP

More information

1 Dynamic Memory continued: Memory Leaks

1 Dynamic Memory continued: Memory Leaks CS104: Data Structures and Object-Oriented Design (Fall 2013) September 3, 2013: Dynamic Memory, continued; A Refresher on Recursion Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we continue

More information

Acknowledgements These slides are based on Kathryn McKinley s slides on garbage collection as well as E Christopher Lewis s slides

Acknowledgements These slides are based on Kathryn McKinley s slides on garbage collection as well as E Christopher Lewis s slides Garbage Collection Last time Compiling Object-Oriented Languages Today Motivation behind garbage collection Garbage collection basics Garbage collection performance Specific example of using GC in C++

More information

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7 CPS109 Course Notes 7 Alexander Ferworn Unrelated Facts Worth Remembering The most successful people in any business are usually the most interesting. Don t confuse extensive documentation of a situation

More information

ITP 342 Advanced Mobile App Dev. Memory

ITP 342 Advanced Mobile App Dev. Memory ITP 342 Advanced Mobile App Dev Memory Memory Management Objective-C provides two methods of application memory management. 1. In the method described in this guide, referred to as manual retain-release

More information

In Java we have the keyword null, which is the value of an uninitialized reference type

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

Memory Usage. Chapter 23

Memory Usage. Chapter 23 C23621721.fm Page 280 Wednesday, January 12, 2005 10:52 PM Chapter 23 Memory Usage The garbage collector is one of the most sophisticated pieces of the Microsoft.NET Framework architecture. Each time an

More information