Garbage Collection Java Interview Questions – Set 03

What is the importance of the destroy() method in Servlet

  • 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…

}

What is the effect when a transient mapped object is passed onto a Sessions save

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.

What are the pros and cons of an Observer design pattern

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.

What is a thread leak? What does it mean in Java

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.