Garbage Collection Java Interview Questions | Eklavya Online

Garbage Collection Java Interview Questions

  • final” is the keyword to declare a constant AND prevents a class from producing subclasses.
  • finally” is a block of code that always executes when the try block is finished, unless System.exit() was called.
  • finalize()” is an method that is invoked before an object is discarded by the garbage collector.

final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.

This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Note: Its an Error (extends java.lang.Error) not Exception. Two important types of OutOfMemoryError are often encountered

  • lang.OutOfMemoryError: Java heap space
    • The quick solution is to add these flags to JVM command line when Java runtime is started:
      • -Xms1024m -Xmx1024m
    • lang.OutOfMemoryError: PermGen space
      • The solution is to add these flags to JVM command line when Java runtime is started:
        • -XX:+CMSClassUnloadingEnabled
        • -XX:+CMSPermGenSweepingEnabled

Long Term Solution: Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks. You can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place.

java.util.Comparator
java.util.Comparator compares some other class’s instances.

java.lang.Comparable
java.lang.Comparable compares another object with itself.

Differentiate between final, finally and finalize.

The keyword is final. It is used for declaring a constant It prevents a class from producing subclasses.

finally is a code.It always executes when the try block is finished, Unless System.exit() has been called.finalize() is a method, Before discarding by the garbage collector it is invoked.

Differentiate JAR and WAR files

JAR files:

  • JAR files is the acronym stands for Java ARchive fles.
  • JAR files allow aggregating many files into one,
  • JAR is usually used to hold Java classes in a library.

WAR files:

  • WAR files is the acronym stands for Web ARchive fles.
  • WAR stores XML, java classes, and JavaServer pages
  • WAR is mainly used for Web Application purposes.

In a Java , how can you send program messages on the system console, but error messages, to a file?

The class System has a variable out that denotes the standard output.

The standard error device represents the variable err .

Naturally, they both point at the system console.

 

In this way, the standard output can be sent to the file:

Stream x = new Stream(new FileOutputStream(“error.txt”));

System.setErr(x);

System.Out(x);

An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

The garbage collector invokes an object’s finalize() method when it detects that the object has become unreachable.

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread

The runtime system keeps track of the memory that is allocated and is able to

determine whether that memory is still useable. This work is usually done in

background by a low-priority thread that is referred to as garbage collector. When the

gc finds memory that is no longer accessible from any live thread it takes steps to

release it back to the heap for reuse

A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected..

Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. This frees the programmer from having to keep track of when to free allocated memory, thereby preventing many potential bugs. Thus making programmers more productive as they can now put more effort in coding rather than worrying about memory management.

The only disadvantage of garbage collector is it adds overheads. Because the JVM (Java virtual machine) has to keep a constant track of the objects which are not referenced and then free these unreferenced objects on fly. This whole process has a slight impact on the application performance. But garbage collector has a good algorithm and it runs in its own thread thus having a least impact on the application performance but still it has some impact.

When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

Garbage collector can be run forcibly using “System.gc()” or “Runtime.gc()”

finalize () method is used just before an object is destroyed and can be called just prior to garbage collection

An object’s finalize() method may only be invoked once by the garbage collector

Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

  • The servlet is initialized by calling the init ()
  • The servlet calls service()method to process a client’s request.
  • The servlet is terminated by calling the destroy()
  • Finally, servlet is garbage collected by the garbage collector of the JVM.

 

  • The destroy() method is called only once at the end of the life cycle of a servlet.
  • This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
  • After the destroy() method is called, the servlet object is marked for garbage collection.

It can be used to “clean up” environments such as database connections.

public void destroy()

{

// Finalization code…

}

When a session.save( ) is passed to a transient mapped object it makes the method to become more persistent. Garbage collection and termination of the Java virtual machine stays as long as it is deleted explicitly. It may head back to its transient state.

PROS:                                                

  • Loose coupling between Subject and Observer: The subject knows only a list of observers, that implementthe Observer interface, it does no know the concrete implementation of the Observer.
  • Broadcast communication: An eventnotification is broadcast to observers irrespective of the number of Observers

CONS:                                               

  • If not used carefullythe observer pattern can add unnecessary complexity.
  • The order of Observer notifications is undependable. Simply registering the observers in a particular order will not enforce their order ofnotification. You don’t necessarily know if the first registered listener is notified first or last. If you need to have cascading notifications, where object X must be notified first, followed by object Y, you must introduce an intermediary object to enforce the ordering.
  • The possibility of a memory leak: A reference tothe Observer is maintained by the Subject. Until the Subject releases the reference, the Observer cannot be removed by the garbage collector.

Thread leak is when a application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang.