Thursday, May 15, 2008

Java Garbage Collection

A garbage collector is responsible for
  • allocating memory
  • ensuring that any referenced objects remain in memory, and
  • recovering memory used by objects that are no longer reachable from references in executing code.

Space is allocated by a large space called heap. The JVM's heap stores all objects created by an executing Java program. Objects are created by Java's "new" operator, and memory for new objects is allocated on the heap at run time.

In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap fragmentation occurs through the course of normal program execution. New objects are allocated, and unreferenced objects are freed such that free blocks of heap memory are left in between blocks occupied by live objects

Code for System.gc is as follows

public static void gc() {
Runtime.getRuntime().gc();
}


System.gc() is just more convinient to call/use

freeMem = Runtime.getRuntime().freeMemory();
System.gc();
System.out.println("free memory after running gc(): " + freeMem);


Interesting links
http://chaoticjava.com/posts/garbage-collection-the-comic-panel/
http://chaoticjava.com/posts/how-does-garbage-collection-work/
http://chaoticjava.com/posts/parallel-and-concurrent-garbage-collectors/
http://chaoticjava.com/posts/gc-tips-and-memory-leaks/

Wednesday, May 14, 2008

Java and MS-Office

Just in case ever need to
  1. Read a Microsoft word document in Java
  2. Import Excel in JTable
In Conference Java One 2008 , Oracle also gave demo on how to integrate MS-Excel with ADF

Java Strings Immutable

Many modern languages (like java) employ “the immutable object” paradigm, which solves a lot of problems including the
  1. Memory conservation
  2. Addressing concurrency concerns
  3. Cache localization
Memory Conservation - A pool of string objects ( constant ) is maintained with references pointing to the constant objects. Instead of each variable having new String object. Re usability leads to lesser memory usage.

Concurrency Concerns - if you change any string need to consider that more than one references may be pointing to same string , so if you will change that string all references must also be updated ( thats tough ) so a new object for changed string will be created and only that particular reference will be point to that new object hence actual object will never change.

I am not sure about cache localization ??

Linux : how to list directory only

To see a listing of all directories in current directory

  • ls -l | grep ^d ( this will show names with details )
  • ls -d */ ( will how names only )

If you want to see hidden directory also
  • ls -d .*"/" *"/"
  • find . -type d -exec ls -d {} \;
  • find . -type d

Tuesday, May 13, 2008

JavaScript : String Performance

Just wanted to book mark these two "excellent" blog entries ...
  1. http://ajaxian.com/archives/everything-you-wanted-to-know-about-string-performance
  2. http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/

Servlets and Garbage Collection

Basic Cycle
  1. The destroy() method is called by the servlet container when the container decides to unload the servlet instance itself.
  2. After the destroy() method completes, the servlet engine unloads the servlet,.
  3. Then, the JVM eventually performs garbage collection on the memory resources associated with that servlet object.
Effecient Servlet : Goals

When can you say that a Servlet is efficient , well of course when it does your work in most effecient manner or in other words the algorithm/logic that you have in it is effecient... but there's more to its efficiency .. Read On !!

Secondly even for High volume Web applications, one needs to carefully control the amount of garbage created during page generation. More the garbage created, fewer the pages generated, and the slower is the response time for a particular request. ( This bottleneck occurs because the Java VM has to steal cycles to run garbage collection when it should be generating pages. ) On the flip side , if too much garbage is created, request processing could halt entirely. Which is unacceptable.


Third is to keep the browser active: not too much of "waiting for response" messages. To put it in programatic terms the time a bean spends querying backend is the time a user spends waiting for page to display. This can -- and should -- be avoided using servlet response streaming techniques.

All About Servlets : Run The Servlet


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.*;

public class AllAboutServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

public AllAboutServlet() {
System.out.println("CTOR : Servlet constructor can be overriden .. " +
"should not be private , protected , nor default");
System.out.println("CTOR : The ctor will be called by the container ... ");
System.out.println("CTOR : At present its a normal java object .. " +
"doesnt understand ServletContext and ServletConfig ");
System.out.println("CTOR : Servlets are usually instantiated by the servlet " +
"container using the Class.newInstance() method, with no arguments");
}

private AllAboutServlet(int i){
System.out.println("Parameterized ctor value "+i);
System.out.println("It is possible to have a custom constructor for a servlet, " +
"so long as you also add a default constructor with no arguments ?? WHY ??");
System.out.println("the servlet gets instantiated by the container dynamically");
System.out.println("java does not allow to call parametrized constuctor for dynamically " +
"loaded clases");
}

public static void static_method(){
System.out.println("Can have Static method in servlet .. who can call it ??");
System.out.println("Probably no one is stopping other classes to use servlet to" +
"instantiate amnd use it as a normal object ");
System.out.println("Other classes may even call init() service() and then destroy() " +
"that wont make it servlet.. unless container call");
System.out.println("Only container can use servlet class as a servlet ");
}

public void init(ServletConfig config) throws ServletException {
System.out.println("INIT : Servlet init called .. now java object turns servlet .. " +
"understands ServletContext and ServletConfig");
System.out.println("INIT : perform one-time expensive operations, such as acquiring " +
"thread-safe resource acquisition mechanisms ");
// One effective use of the Servlet init method is the creation and caching of
// thread-safe resource acquisition mechanisms, such as JDBC DataSources, EJB Homes,
// and Web Services SOAP Mapping Registry. use this for caching data ...
super.init(config);
// COMPULSORY the abstract superclass implementation of the method in GenericServlet
// stores the servlet configuration object.

// If an exception is thrown in your init(ServletConfig) method, it may be appropriate
// to use the destroy() method to help handle the case. If so, you should still throw
// a ServletException to ensure the servlet is not put into service in this state.
}

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>AllAboutServlet</title></head>");
out.println("<body>");
out.println("<p>The servlet has received a GET. This is the reply.</p>");
out.println("</body></html>");
out.close();

System.out.println("DOGET : doGet called ");
System.out.println("DOGET : one may call delete() from inside service() ... It will do whatever logic you have in destroy() (cleanup, remove attributes, etc.) but it won't \"unload\" the servlet instance itself");
System.out.println("");
}

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>AllAboutServlet</title></head>");
out.println("<body>");
out.println("<p>The servlet has received a POST. This is the reply.</p>");
out.println("</body></html>");
out.close();
}

public void doPut(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
}

public void doDelete(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
}

public void destroy(){
System.out.println("DESTROY : destroy called by contianer .. when is it called ??" +
"When your application is stopped or Servlet Container shuts down ");
System.out.println("DESTROY : Not when embedded oc4j stopped ");
System.out.println("DESTROY : destroy() does not imply garbage collection");
System.out.println("DESTROY : write the destroy() method and destroy your servlet" +
"because if many servlets running on the same webserver are not destroyed explicitly," +
"then the performance of the web server falls down");
System.out.println("DESTROY : destroy() is not guaranteed to be called... but if it is, " +
"you should make sure it works right");
}

public void destroy(int i){
System.out.println("may overload .. its syntactically ok ... container wont call this...");
}

public void point1() {
System.out.println("Is it possible that the servlet container will call destroy()" +
"while the servlet is still processing a request inside service() on a different thread ?");
System.out.println("yes, but it's a degenerate case. The servlet container is required" +
"to wait a reasonable amount of time for current requests to finish processing. So if your" +
"request is not totally lagging, it should work out fine. If you're spending more than" +
"a few seconds processing a request, that's a UI problem that you should try to work out first.");
}
public void point2() {
// GenericServlet has methods ... init() destroy() log() getInitParameter() getInitParameterNames()
// getServletContext() getServletConfig() getServletInfo() getServletName()
}
public void point3() {
// HttpServlet is declared abstract because the default implementations of the main service methods
// do nothing and must be overridden
}
public void point4() {
// The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it
// easy for developers to create custom implementations of the servlet request and response types.
// The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances
// respectively and their default behaviour is to pass all method calls directly to the underlying
// objects.
}

}