Monday, April 28, 2008

Recursion in Java

public void handleParent(int parentOid){

List clientBVOList=this.getClients(parentOid);
for(int i=0;i Lessthan clientBVOList.size();i++){
NcClient nc=(NcClient)clientBVOList.get(i);
if(nc.getNotchParentFl().equalsIgnoreCase("T")){

handleParent(parentOid-1);
resetFacs(nc);
}else{
resetFacs(nc);
}

}

}


private void resetFacs(NcClient nc) {
// TODO Auto-generated method stub

System.out.println("Resetting facilities for Client:"+nc.getName());

}


private List getClients(int parentOid) {
// TODO Auto-generated method stub
List ncList=new ArrayList();
if(parentOid==3){
System.out.println("Get clients for Parent 3");
NcClient nc=new NcClient("client1","F");
NcClient nc2=new NcClient("Client2","T");
NcClient nc3=new NcClient("Client3","F");
ncList.add(nc);
ncList.add(nc2);
ncList.add(nc3);
return ncList;
}
if(parentOid==2){
System.out.println("Get clients for Parent 2");
NcClient nc=new NcClient("client2.1","F");
NcClient nc2=new NcClient("Client2.2","T");
ncList.add(nc);
ncList.add(nc2);
return ncList;
}

if(parentOid==1){
System.out.println("Get clients for Parent 1");
NcClient nc =new NcClient("Client2.2.1","F");
NcClient nc2=new NcClient("Client2.2.2","F");
ncList.add(nc);
ncList.add(nc2);
return ncList;
}

return null;
}

NC Client:

public class NClient {

String nParentFl;
String name;

public NClient(String name,String parentFl){
this.name=name;
this.nParentFl=parentFl;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNParentFl() {
return nParentFl;
}
public void setNParentFl(String nParentFl) {
this.nParentFl = nParentFl;
}

}

Result:

Get clients for Parent 3
Resetting facilities for Client:client1
Get clients for Parent 2
Resetting facilities for Client:client2.1
Get clients for Parent 1
Resetting facilities for Client:Client2.2.1
Resetting facilities for Client:Client2.2.2
Resetting facilities for Client:Client2.2
Resetting facilities for Client:Client2
Resetting facilities for Client:Client3

Friday, April 25, 2008

So Small Lyrics

Carrie Underwood So Small Lyrics

While working lost in a busy day.. this song came from ipod like a refreshing spring shower ...quickly looked up lyrics on the internet..and pasting here. Another reason why I love my ipod so much.. :)).. sometimes it brings me out of my lostness.

Yeah, Yeah
What you got if you ain't got love
the kind that you just want to give away
its okay to open up
go ahead and let the light shine through
I know it's hard on a rainy day
you want to shut the world out and just be left alone
but don't run out on your faith

'cause sometimes that mountain you've been climbing
is just a grain of sand
and what you've been up there searching for forever
is in your hands
when you figure out love is all that matters after all
it sure makes everything else seem so small

it's so easy to get lost inside
a problem that seems so big at the time
it's like a river thats so wide
it swallows you whole
while you siting 'round thinking 'bout what you can't change
and worrying about all the wrong things
time's flying by
moving so fast
you better make it count 'cause you cant get it back

sometimes that mountain you've been climbing
is just a grain of sand
and what you've been up there searching for forever
is in your hands
oh when you figure out love is all that matters after all
it sure makes everything else seem so small

sometimes that mountain you've been climbing
is just a grain of sand
and what you've been up there searching for forever
is in your hands
oh when you figure out love is all that matters after all
it sure makes everything else...
oh it sure makes everything else seem so small
Yeah, Yeah

-- Playin the song agin. :D

Thursday, April 24, 2008

JConsole

Using JConsole

The JConsole graphical user interface is a monitoring tool that complies to the Java Management Extensions (JMX) specification. JConsole uses the extensive instrumentation of the Java Virtual Machine (Java VM) to provide information about the performance and resource consumption of applications running on the Java platform.

In the Java Platform, Standard Edition (Java SE platform) 6, JConsole has been updated to present the look and feel of the Windows and GNOME desktops (other platforms will present the standard Java graphical look and feel). The screen captures presented in this document were taken from an instance of the interface running on Windows XP.

1) You can use JConsole to monitor both local applications, namely those running on the same system as JConsole, as well as remote applications, namely those running on other systems
2) For monitoring production systems, use remote monitoring
3) Configure your jvm to run with JMX
3) Starting JConsole:
1) Have java Home in ur class path or open ur cmd prompt at C:\bea92\jrockit90_150_06\bin
2) type jconsole [processId] ex: jconsole 7280
4) Start remote JVM
type jconsole hostName:portNum




Using JConsole

Performance issues and Tools to use

Insufficient Memory

The Java Virtual Machine (JVM)* has the following types of memory: heap, non-heap, and native.

3 Types:
1) Heap Memory Error
2) Non Heap Memory Error
3) Native Memory Error

Memory Leaks

The JVM is responsible for automatic memory management, which reclaims the unused memory for the application. However, if an application keeps a reference to an object that it no longers needs, the object cannot be garbage collected and will occupy space in the heap until the object is removed. Such unintentional object retention is referred to as a memory leak. If the application leaks large amounts of memory, it will eventually run out of memory, and an OutOfMemoryError will be thrown. In addition, garbage collection may take place more frequently as the application attempts to free up space, thus causing the application to slow down.

Finalizers

Another possible cause of an OutOfMemoryError is the excessive use of finalizers. The java.lang.Object class has a protected method called finalize. A class can override this finalize method to dispose of system resources or to perform cleanup before an object of that class is reclaimed by garbage collection. The finalize method that can be invoked for an object is called a finalizer of that object. There is no guarantee when a finalizer will be run or that it will be run at all. An object that has a finalizer will not be garbage collected until its finalizer is run. Thus, objects that are pending for finalization will retain memory even though the objects are no longer referenced by the application, and this could lead to a problem similar to a memory leak.


Deadlocks

A deadlock occurs when two or more threads are each waiting for another to release a lock. The Java programming language uses monitors to synchronize threads. Each object is associated with a monitor, which can also be referred as an object monitor. If a thread invokes a synchronized method on an object, that object is locked. Another thread invoking a synchronized method on the same object will block until the lock is released. Besides the built-in synchronization support, the java.util.concurrent.locks package that was introduced in J2SE 5.0 provides a framework for locking and waiting for conditions. Deadlocks can involve object monitors as well as java.util.concurrent locks.

Typically, a deadlock causes the application or part of the application to become unresponsive. For example, if a thread responsible for the graphical user interface (GUI) update is deadlocked, the GUI application freezes and does not respond to any user action.


Looping Threads

Looping threads can also cause an application to hang. When one or more threads are executing in an infinite loop, that loop may consume all available CPU cycles and cause the rest of the application to be unresponsive.


High Lock Contention

Synchronization is heavily used in multithreaded applications to ensure mutually exclusive access to a shared resource or to coordinate and complete tasks among multiple threads. For example, an application uses an object monitor to synchronize updates on a data structure. When two threads attempt to update the data structure at the same time, only one thread is able to acquire the object monitor and proceed to update the data structure. Meanwhile, the other thread blocks as it waits to enter the synchronized block until the first thread finishes its update and releases the object monitor. Contended synchronization impacts application performance and scalability.

Problem: Insufficient memory
Symptom: OutOfMemoryError
Tool: Java Heap Analysis Tool (jhat)

Problem: Memory leaks Growing use of memory
Symptom: Frequent garbage collection Java Monitoring and Management Console (jconsole)
Tool: JVM Statistical Monitoring Tool (jstat)

Symptom: A class with a high growth rate. A class with an unexpected number of instances Memory Map (jmap)
An object is being referenced unintentionally jconsole or jmap with jhat
Tool: See jmap -histo option
See jmap -dump option

Problem: Finalizers
Symptom: Objects are pending for finalization jconsole
Tool: jmap -dump with jhat

Problem: Deadlocks Threads block on object monitor or
Symptom: java.util.concurrent locks jconsole
Tool: Stack Trace (jstack)

Problem: Looping threads
Symptom: Thread CPU time is continuously increasing
Tool: jconsole with JTop

Problem: High lock contention
Symptom: Thread with high contention statistics
Tool: jconsole

Had a great time exploring performance monitors.

-Knowledge is power.

Friday, April 18, 2008

Internationalization in Struts

Def: Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text.

How do we achieve this in Struts.. very simple. Struts comes with built in support for interanationalization.

by default you have applicationResources.properties file, which supports the default locale english. Now for every additional language you wish to support, create a new applicationResources_{Locale u r adding}.properties.

example: For Hindi create a file called,

ApplicationResources_hi.properties file and put all ur messages in a key, value format.

Ex: in ApplicationResources.properties (default for english) you define messages like
page.title=Thank you for visiting!

now for Hindi.. you'll have a file like
ApplicationResources_hi.properties
page.title=Dhanyawaad!


And define both files in ur struts-config.xml file, in message resources section

{message-resources
parameter="com.sunny.app.ApplicationResources" /}

{message-resources
parameter="com.sunny.app.ApplicationResources_hi" /}


Calling From JSP:

{h2}{bean:message key="page.title"/}{/h2}

Thats it depending on ur locale.. apt file will be invoked and apt msg in ur language is shown on screen.

Testing: To change locale of ur browser.. goto

tools-->internet options-->languages --> add-->

choose hindi add and move it to the top.

Now when you run your application, message is displayed in Hindi...:D


This is too cool and exciting..!!!

Friday, April 11, 2008

ConcurrentModificationException

Problem Def: java.util.ConcurrentModificationException, occurs when you iterate thur and modify the same List of values.

Solution: Tried using a for loop, List.iterator, Collections.synchronizedList() all in vain. With for loop, I often ran into array index out of bound. Using iterator got ConcurrentModification error. So the solution is copy your values into another list and modify new list while iterating the old one.

Wait a minute.. googling longer found a better answer.. you should use iterator.remove() yay..!!! effective way of all:D


Lesson learnt: Patience pays off


Happy reading
Sunny
-------------

Thursday, April 10, 2008

Garbage Collector

Dont gimme that look... :) I am talking about JVM's (Java Virtual Machine's) Garbage collector.

Automatic Garbage Collection is one of the most convenient features in Java, which promises to prevent memory leaks unlike in C or C++, where programmer has to manuallly allocate and de-allocate memory using malloc,calloc/de-alloc functions.

Lets learn the inner workings of GC. Excerpts of an article from Sun:

GC def: is a benevolent sentinel present in every JVM. Its role is to identify and free chunks of memory left unused by the currently running application. Its job should shed some light on the origin of the name "garbage collector." Despite the depreciating name, the GC is like Dilbert's garbage man who is very smart, even smarter than you sometimes.

During its lifecycle, an application creates a certain number of objects, that is to say a certain amount of data that consumes memory and lasts according to its role in the application. As a matter of fact, an application spawns a large amount of short-lived objects during its life span. So you can understand that defining and controlling the lifecycle of every single object generated by an application demands a tremendous amount of work from developers.

A simple example should give you a better idea of the incredible number of objects that are born and then killed. When you open a plain text file in a text editor, in our case Jext, 342,997 objects are created and destroyed.

A memory leak is caused by objects, called undeads or zombies, left unused but still marked alive in memory. The more undeads wandering about, the more memory the application will need. The program eventually runs of out fresh memory and crashes. Good memory management is one of the most difficult issues in low-level languages like C or C++. Some high-level languages, like Java or Python, rely on a GC that cuts down the programmer's workload. So a developer supported by a GC only needs to do object creation.

Although extremely convenient, a GC is not a miracle tool and every so often does wicked things



Parts of a JVM Heap:

The GC in the HotSpot JVM is also called the "generational garbage collector." As its name suggests, this GC can make a difference to several generations of objects. Within the virtual machine, objects are born, live, and die in a memory area known as the heap.

The heap itself is divided into two parts, each one corresponding to a given generation: the young space and the tenured space. The first hosts recent objects, also called children, while the second one holds objects with a long life span, also called ancestors. Next to the heap, the virtual machine contains another particular memory area, called the perm, in which the binary code of each class loaded by the currently executing program is archived. Although the perm is important to applications dynamically generating a lot of bytecode, like a J2EE server, it's unlikely you'll ever need to tweak it.


Both the tenured space and the young space contain a virtual space, a zone of memory available to the JVM but free of any data. That means that those spaces might grow and shrink with time

Whenever a new object is allocated to the heap, the JVM puts it in the eden.The GC uses the one that remains free as a temporary storage bucket. When the young space gets overcrowded, a minor collection is done. A very simple copy algorithm is used that involves the free survivor space. During a minor collection, the GC runs through every object in both the eden and the occupied survivor space to determine which ones are still alive, in other words which still have external references to themselves. Each one of them will then be copied into the empty survivor space.


In the tenured space the laws are different. Whenever more memory is needed, a major collection is done with the help of the Mark-Sweep-Compact algorithm. Though it's not complex, it's greedier than the copy algorithm. The GC will run through all the objects in the heap, mark the candidates for memory reclaiming, and run through the heap again to compact remaining objects and avoid memory fragmentation. At the end of this cycle, all living objects exist side-by-side in the tenured space. The major collections responsible for most Java applications slow down from time to time. Unlike a minor collection, running a major collection stops the execution of the whole application. So a good optimization trick is to reduce the burden of the Mark-Sweep-Compact algorithm.


Parameters of JVM Heap:
-Xms{size} specifies the minimal size of the heap. This option is used to avoid frequent resizing of the heap when your application needs a lot of memory.
-Xmx{size} specifies the maximum size of the heap. This option is used mainly by server-side applications that sometimes need several gigs of memory. So the heap is allowed to grow and shrink between the two values defines by the –Xms and –Xmx flags.
-XX:NewRatio={number} specifies the size ratio between the tenured space and the young space. For instance, -XX:NewRatio=2 would yield a 64MB tenured space and a 32MB young space, together a 96MB heap.
-XX:SurvivorRatio={number} specifies the size ratio between the eden and one survivor space. With a ratio of 2 and a young space of 64MB, the eden will need 32MB of memory whereas each survivor space will use 16MB.