Java basics 4

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What happens during garbage collection?

1. Initially when objects are instantiated, they are designated to the Eden bucket (Young generation) 2. Then minor garbage collection occurs. After a few cycles of minor garbage collection, if an object has survived each minor garbage collection, JVM recognizes it as important and moves it to the Old memory bucket

What is a design pattern?

A bunch of rules for problems that occur very commonly in every application There are ~14-15 design patterns

What is a singleton?

A design pattern where the amount of instances a class is allowed to have is restricted to one

What is a fixture?

A fixture is a fixed state of a set of objects used as a baseline for running tests. The purpose of a fixture is to make sure there is a well known and fixed environment in which tests are run so that results are repeatable. It includes: - setUp() method - tearDown() method

What is JUnit?

A useful feature of Java that allows us to quickly write unit tests for classes we are writing. The tests can be run repeatedly so that as changes are made to the code we can quickly verify that everything still works properly! It is a testing framework.

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.

Why unit test?

Code quality, Finding bugs early, Cost reduction

What is manual testing?

Executing the test cases manually without any tool support. Disadvantages: - Time consuming and tedious - Huge investment in human resources - Less reliable - Non-programmable

What are the features of JUnit?

Fixtures Test suites Test runners Annotations

What is garbage collection?

Garbage collection is a process of reclaiming the runtime unused objects. It is performed for memory management. It cleans up heap allocations of unneeded objects. It is an automatic process. It is implemented based on JVM specifications

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.

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.

What does the "synchronized" keyword mean?

If more than one thread tries to access a method or block of code that is synchronized, JVM will randomly assign a thread exclusive access until it releases the lock

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 OutOfMemoryError or more specifically java.lang.OutOfMemoryError heap space.

What is the "young generation"?

It is comprised of the Eden bucket, and S0 + S1 (survivor space 0 and survivor space 1)

What is the "old generation"?

It is comprised of the Old memory bucket

How do you prevent deadlocks?

Lock timeout Lock ordering

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.

Q12. Describe Strong, Weak, Soft and Phantom References and Their Role in Garbage Collection.

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. By default, every object we create in a Java program is strongly referenced by a variable: 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: 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. A soft reference can be created to the above object like this: StringBuilder sb = new StringBuilder(); SoftReference<StringBuilder> sbRef = new SoftReference<>(sb); sb = null; In the above snippet, we have created two references to the StringBuilder object. The first line creates a strong reference sb and the second line creates a soft reference sbRef. The third line should make the object eligible for collection but the garbage collector will postpone collecting it because of sbRef. The story will only change when memory becomes tight and the JVM is on the brink of throwing an OutOfMemory error. In other words, objects with only soft references are collected as a last resort to recover memory. 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. A 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.

Synchronization

Multithreading, shared objects, and resources Race conditions Only needed for mutable shared objects Keywords: synchronized and volatile

Do we touch permgen space?

No, we do not touch it

What is the difference between method-level and block-level synchronization?

Normally, don't add synchronization at the method level. Block synchronization is making a portion or BLOCK of code synchronized

What is the producer/consumer problem?

Situation: One or more producers are generating data and placing these in a buffer. A single consumer is taking items out of the buffer one at a time. Only one producer or consumer may access the buffer at any one time. The problem is to ensure that the producer can't add data into full buffer and consumer can't remove data from an empty buffer

What is a test runner?

Software that runs your tests

What is synchronization?

Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.

Deadlock

Synchronized / thread safety

What is automated testing

Taking tool support and executing the test cases by automation tool. Advantages: - Fast - Less investment in human resources - More reliable - Programmable

What are TDD and TFD? And

Test Driven Development. You write the tests to help guide your design and development. Test First Development is apart of TDD where you write the unit tests and test cases before programming, then run them periodically while you go.

What is a test suite?

Test suites are bundles of individual unit test cases that run together. Both @RunWith and @Suite annotations can be used for test suites

What is testing?

Testing is the process of checking the functionality of the application whether it is working per requirements

How is the JVM (Java memory) formatted?

The Java memory is divided into two parts: the stack and the heap

What is the heap?

The heap is the region in memory where Objects are stored. When objects are no longer being used, that memory is "recycled" automatically so that it can be used by other Objects later. The heap is what the developer has to control and make sure it doesn't overflow

What is "permgen" space?

The permgen space is a space for permanent generation where all the JVM-level methods and memory objects sit

Q5. What Are Stack and Heap? What Is Stored in Each of These Memory Structures, and How Are They Interrelated?

The stack is a part of memory that contains information about nested method calls down to the current position in the 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 new keyword, it gets allocated on the heap. However, the reference to this object lives on the stack.

What is on the stack?

The stack is where all the static files that don't run on runtime sit

What are "System.gc()" and "runtime.gc()" and what is the difference?

These are methods that, when called, SUGGEST to JVM to perform garbage collection -- although this isn't a guarantee JVM will Functionally, there is no difference between the two. System.gc() is a class method while runtime.gc() is an instance method

Q7. Describe in Detail How Generational Garbage Collection Works

To properly understand how generational garbage collection works, it is important to first remember how Java heap is structured to facilitate generational garbage collection. The heap is divided up into smaller spaces or generations. These spaces are Young Generation, Old or Tenured Generation, and Permanent Generation. The young generation hosts most of the newly created objects. An empirical study of most applications shows that majority of objects are quickly short lived and therefore, soon become eligible for collection. Therefore, new objects start their journey here and are only "promoted" to the old generation space after they have attained a certain "age". The term "age" in generational garbage collection refers to the number of collection cycles the object has survived. The young generation space is further divided into three spaces: an Eden space and two survivor spaces such as Survivor 1 (s1) and Survivor 2 (s2). The old generation hosts objects that have lived in memory longer than a certain "age". The objects that survived garbage collection from the young generation are promoted to this space. It is generally larger than the young generation. As it is bigger in size, the garbage collection is more expensive and occurs less frequently than in the young generation. The permanent generation or more commonly called, PermGen, contains metadata required by the JVM to describe the classes and methods used in the application. It also contains the string pool for storing interned strings. It is populated by the JVM at runtime based on classes in use by the application. In addition, platform library classes and methods may be stored here. First, any new objects are allocated to the Eden space. Both survivor spaces start out empty. When the Eden space fills up, a minor garbage collection is triggered. Referenced objects are moved to the first survivor space. Unreferenced objects are deleted. During the next minor GC, the same thing happens to the Eden space. Unreferenced objects are deleted and referenced objects are moved to a survivor space. However, in this case, they are moved to the second survivor space (S2). In addition, objects from the last minor GC in the first survivor space (S1) have their age incremented and are moved to S2. Once all surviving objects have been moved to S2, both S1 and Eden space are cleared. At this point, S2 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 S1 from both Eden and S2. Surviving objects are aged. Eden and S2 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. This pretty much exhausts the process of garbage collection in the young generation. Eventually, a major garbage collection will be performed on the old generation which cleans up and compacts that space. For each major GC, there are several minor GCs.

How many types of garbage collection are there?

Two types: minor and major

What is unit testing?

Unit testing is the testing of a single entity (class or method). Unit testing is very essential to give a quality product to customers

What does the "volatile" keyword mean?

Used to acquire thread-safety on variables

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.

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.

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.

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.

What are the JUnit fixtures?

setUp() method --> Runs before every test invocation tearDown() method --> Runs after every method


Set pelajaran terkait

Erin's study guide Transactional Analysis

View Set

Chapter 23 Terrestrial Ecosystems

View Set

interventions week 9 fluid and electrolye prepU questions

View Set

ANFI 205 (REF 1-2): The Purpose in Passing the National Flood Insurance Act of 1968

View Set