Showing posts with label Java J2EE. Show all posts
Showing posts with label Java J2EE. Show all posts

Friday, October 5, 2012

Create Java inline thread

import java.util.Date;

public class InlineThreadDemo {
 public static void main(String[] args) {
System.out.println( "parent thread " + new Date(System.currentTimeMillis())); // launch child thread using
// inline declaration
new Thread( new Runnable() {
public void run() {
try {
Thread.sleep(10 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println( "child thread " + new Date(System.currentTimeMillis()));
}
}).start();

System.out.println( "parent thread " + new Date(System.currentTimeMillis())); }}


Thursday, December 2, 2010

Closing a Swing Application

Just calling toplevel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); is not good enough.
There could be other frames still alive, esp if you are using a third party library.
So your JVM is still running. Here is how you fix it..
Get all the frames that are currently running and dispose each of them

Frame[] frames = toplevel.getFrames();

for(int i=0;i
Frame frame = frames[i];
frame.dispose();
}
-Sonu

Friday, January 29, 2010

Eclipse VM Args

Multiple VM args can be entered to eclipse by separating them with a space. See the picture below :




2) Issue : Eclipse doesnot allow spaces in vm arguments.

You can force eclipse to take a space by wrapping the value of your argument in double quotes.

-Dpropsfile="H:/user data/eclipse/workspace/wires/etc/dev.config.props"

Cheers,
Sonu

Tuesday, August 25, 2009

Serialization in java

Question: What are the uses of Serialization?

Answer: In some types of applications you have to write the code to serialize objects, but in many cases serialization is performed behind the scenes by various server-side containers.

These are some of the typical uses of serialization:

To persist data for future use.
To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
To "flatten" an object into array of bytes in memory.
To exchange data between applets and servlets.
To store user session in Web applications .
To activate/passivate enterprise java beans.
To send objects between the servers in a cluster

Java Threads

Good overview:

http://www.cs.usfca.edu/~parrt/course/601/lectures/threads.html

Sunday, August 16, 2009

Volatile Variables in Java

What does volatile do?

This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:

int i1; int geti1() {return i1;}
volatile int i2; int geti2() {return i2;}
int i3; synchronized int geti3() {return i3;}
geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.

Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:


1.The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
2.The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
3.The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
4.(Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
5.The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

Source : http://www.javaperformancetuning.com/news/qotm030.shtml

Monday, August 10, 2009

Designing Thread Safe Classes in Java

http://www.artima.com/designtechniques/threadsafety.html

Monday, October 13, 2008

Reflection in Java

Creating a object using reflection in Java:

Class parserClass=Class.forName(parser);
Object newParser=parserClass.newInstance();
Class classParams[]=new Class[1]; //To set type of parameter
Object arglist[]=new Object[1]; //To set the actual value

classParams[0] = String.class;
arglist[0] = tradeType;
String methodName="setLoadType";

Method meth = parserClass.getMethod(methodName, classParams);

meth.invoke(newParser, arglist); //Set setTradeType=tradeType

return (DefaultFileParser)newParser;


StringArrayConvertor in Java

public Object convert(Class type,
Object value)
Deprecated.
Convert the specified input object into an output object of the specified type.
If the value is already of type String[] then it is simply returned unaltered.
If the value is of type int[], then a String[] is returned where each element in the string array is the result of calling Integer.toString on the corresponding element of the int array. This was added as a result of bugzilla request #18297 though there is not complete agreement that this feature should have been added.
In all other cases, this method calls toString on the input object, then assumes the result is a comma-separated list of values. The values are split apart into the individual items and returned as the elements of an array. See class AbstractArrayConverter for the exact input formats supported.
Converting Strng Array to String in Java
public static String arrayToString(String[] a, String separator) {
StringBuffer result = new StringBuffer();
if (a.length lt 0) {
result.append(a[0]);
for (int i=1; i lt a.length; i++) {
result.append(separator);
result.append(a[i]);
}
}
return result.toString();
}

Saturday, September 20, 2008

Java Mail API examples

Mail w/o attachments
public class SendJavaMail
{
public static void main(String[] args)
{
try
{
// Create a properties file containing the host address of
// your SMTP server
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", "smtp.myispserver.net");
// Create a session with the Java Mail API
Session mailSession =
Session.getDefaultInstance(mailProps);
// Create a transport object for sending mail
Transport transport = mailSession.getTransport("smtp");
// Create a new mail message
MimeMessage message = new MimeMessage(mailSession);
// Set the From and the Recipient
message.setFrom(new InternetAddress(
"senorcoffeebean@wutka.com"));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress("mark@wutka.com"));
// Set the subject
message.setSubject("Hello from Java Mail!");
// Set the message text
message.setText("Hello!\n"+
"It is I, Senor Coffee Bean! I bring you greetings \n"+
"from the Java Mail API!. \n"+
" Senor Coffee Bean, Esp.\n");
// Save all the changes you have made to the message
message.saveChanges();
// Send the message
transport.send(message);
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
}
public class SendJavaMail
{
public static void main(String[] args)
{
try
{
// Create a properties file containing the host address of
// your SMTP server
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", "smtp.myispserver.net");
// Create a session with the Java Mail API
Session mailSession =
Session.getDefaultInstance(mailProps);
// Create a transport object for sending mail
Transport transport = mailSession.getTransport("smtp");
// Create a new mail message
MimeMessage message = new MimeMessage(mailSession);
// Set the From and the Recipient
message.setFrom(new InternetAddress(
"senorcoffeebean@wutka.com"));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress("mark@wutka.com"));
// Set the subject
message.setSubject("Hello from Java Mail!");
// Set the message text
message.setText("Hello!\n"+
"It is I, Senor Coffee Bean! I bring you greetings \n"+
"from the Java Mail API!. \n"+
" Senor Coffee Bean, Esp.\n");
// Save all the changes you have made to the message
message.saveChanges();
// Send the message
transport.send(message);
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
}


Mail w/ attachments and text:
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
/** Uses the Java Mail API to send a message via SMTP. */
public class SendAttachment
{
public static void main(String[] args)
{
try
{
// Create a properties file containing the host address of
// your SMTP server
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", "smtp.myispserver.net");
// Create a session with the Java Mail API
Session mailSession =
Session.getDefaultInstance(mailProps);
// Create a transport object for sending mail
Transport transport = mailSession.getTransport("smtp");
// Create a new mail message
MimeMessage message = new MimeMessage(mailSession);
// Set the From and the Recipient
message.setFrom(new InternetAddress(
"senorcoffeebean@wutka.com"));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress("mark@wutka.com"));
// Set the subject
message.setSubject("Hello from Java Mail!");
// Create the multipart object for doing attachments
MimeMultipart multi = new MimeMultipart();
// Create the message part for the main message text
BodyPart textBodyPart = new MimeBodyPart();
// Set the message text
textBodyPart.setText("Hello!\n"+
"It is I, Senor Coffee Bean! I bring you an attachment \n"+
"from the Java Mail API!. \n"+
" Senor Coffee Bean, Esp.\n");
// Add the body part to the multipart object
multi.addBodyPart(textBodyPart);
// Create an input stream to read the attachment data
FileInputStream in = new FileInputStream("SendAttachment.java");


// Create the body part for the attachment
BodyPart fileBodyPart = new MimeBodyPart(in);
// Give the attachment a filename (the name that appears when someone
// reads the message--it doesn't have to be the same as the file
// you're reading).
fileBodyPart.setFileName("SendAttachment.java");
// Add the attachment to the multipart object
multi.addBodyPart(fileBodyPart);
// The multipart object is the content for the email message
message.setContent(multi);
// Save all the changes you have made to the message
message.saveChanges();
// Send the message
transport.send(message);
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
}

Friday, July 18, 2008

EJB Deployment Issue

I ran into this weird ejb deployment issue lately. It was a working EJB, then I had to add new remote methods to it. So I added them to the remote interface and to the actual java implementation class. Then when I deployed it locally, it some how doesnt seem to recognize my new methods, and when I access it, it simply throws NoSuchMethodFound error. After struggling for 1.5 days , (as though I dont have enough troubles..) figured out that I have an old client jar with the same .class file,(class I am trying to modify) and the server is picking up the classes from the lib folder evern before deploying my .class files in ejb-jar.

So server always tries to read files in the following order:
1) .class files from the lib folder
2) then any of classes in ur war files webroot/web-inf/classes folder

Also in EJB2.0, you dont need to create stubs and skeletons when you make changes and deploy your ear file,

Also when you provide a service jar to any of your remote service callers, all you porvide in the jar is

1) .class files with Home and Remote interfaces.
2) And no no stubs required. :)

You can generate this jar, by selecting the java classes in your eclipse rt click--> export as jar. I would recommned automate it in ur build file so you dont have to do it everytime. :)

-Coding Rocks.. !!!

Monday, June 23, 2008

Tokens in Struts

Purpose: To prevent a page from being re-submitted when user hits refresh or hits submit multiple times or user clicks on back / forward on your browser and hits submit again

Solution: Tokens in Struts 2.0

Token Methods:

The methods we care about are:

saveToken(HttpServletRequest req)
isTokenValid(HttpServletRequest req)
resetToken(HttpServletRequest req)

Once of the basic concept for implementing tokens:

1) Always provide a setupForInsertOrUpdate dispatch method or indvidual Action. You could also break it up into setupForInsert and setupForUpdate if you so desire. Regardless, make sure you always go through this Action method before you go to your form.
2) In your setup method make sure to call "saveToken(request)." This puts a unique key into Session scope and will cause this token to be placed on your resulting JSP.
In your Action's update/insert dispatch method or your Action's execute method, make sure to first check if "isTokenValid(request)." This compares the token in Session with the one submitted through the Request. If they match, the token is valid and it's ok to procede with the update/insert. If they do not match, the user is likely simply resubmitting a stale page so we return from our action immediately. We need to remember before we leave our update/insert method that we call "resetToken(request)" so that we place a new token into Session scope, otherwise the old token will remain and it will match the one on the form and will allow duplicate submisssions.


Example:

public ActionForward setUpForInsertOrUpdate(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.debug("setUpForInsertOrUpdate");
saveToken(request);
EmployeeForm employeeForm = (EmployeeForm)form;
if (isUpdate(request, employeeForm)) {
Integer id = Integer.valueOf(employeeForm.getEmployeeId());
Employee employee = empService.getEmployee(id);
BeanUtils.copyProperties(employeeForm, employee);
}
prep(request);
return mapping.findForward(Constants.SUCCESS);
}



public ActionForward insertOrUpdate(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.debug("insertOrUpdate");
EmployeeForm employeeForm = (EmployeeForm)form;
if ( !isTokenValid(request) ) {
return mapping.findForward(Constants.INVALID_TOKEN);
}
if (validationSuccessful(request, employeeForm)) {
Employee employee = new Employee();
BeanUtils.copyProperties(employee, employeeForm);
if (isUpdate(request, employeeForm)) {
logger.debug("update");
empService.updateEmployee(employee);
} else {
logger.debug("insert" );
empService.insertEmployee(employee);
}
populateEmployees(request);
resetToken(request);
return mapping.findForward(Constants.SUCCESS);
} else {
prep(request);
return mapping.findForward(Constants.FAILURE);
}
}


-Smile ...tokens are making your life easy :D

Wednesday, June 18, 2008

SimpleDateFormat Example in Java

public class DateFormattingTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

String myDate="Fri Dec 07 17:58:41 EST 2007";
SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd yyyy hh:mm:ss:Sa");
try{

Date d1=sdf.parse(myDate);

String s1=sdf2.format(d1);

System.out.println("Date d1 is :"+d1);
System.out.println("Formatted String is :"+s1);

}catch(Exception e){
System.out.println("Date Parsing Exception");

}

}

}


Usage: When you have a String, and if you want to convert it into a java.util.Date,
SimpleDateFormat's instance should indicate the format of your input string for java to parse and convert it into a Date:

Ex: String myDate="Fri Dec 07 17:58:41 EST 2007";

SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");sdf should tell java the format of your input string for it to be able to parse it to a date like:

//Input is a String
//sdf indicates the format of date in i/p String
//Output is a Date


Date d1=sdf.parse(myDate);

Scenario 2: When you have a Date and if you want to convert it into a String,

your SimpleDateFormat object should indicate the format you wish to convert your string into and use format in this case.

ex: SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd yyyy hh:mm:ss:Sa");

//Input is Date
//sdf indicates the format of the String you wish to see it as output
//Output is formatted String


String s1=sdf2.format(d1);

Friday, June 13, 2008

Increase virtual memory in eclipse

Increasing JVM's virtual memory to avoid core dumps or Out of Memory Error.

1) rt click on ur eclipse.exe or on the shortcut on ur desktop
2) goto shortcut tab and in target specify the jvm vmargs parameter as Xms and Xmx properties.

C:\Suneetha\Dwnld\eclipse\eclipse.exe -product com.genuitec.myeclipse.product.ide -vmargs -Duser.language=en -Xms256M -Xmx512M -XX:PermSize=128M -XX:MaxPermSize=256M


--Sunny

Thursday, June 5, 2008

Regular Expressions in Java

Regular Expressions in Java:

A regular expression works by matching a String against a template or pattern (a Pattern object in Java), and in its simplest form, returning a boolean to say "yes, the string does look like the pattern" or "no, that doesn't match".

As of release 1.4 of Java, though, there's a standard package
java.util.regex
that's shipped with the JRE, and that's what we'll look at in this module.
"^\\S+@\\S+$"

is a regular expression to see if the string entered is an e-mail

Ex:

Pattern email = Pattern.compile("^\\S+cat\\S+$");

Matcher match=email.matcher("vandicated");
if(match.matches()){
System.out.println("Matches vindicated pattern");
}else{
System.out.println("No Match found");
}


If you want to match at the start of a String, start your pattern with a ^ character; if you want to match at the end, conclude your pattern with a $ character. Should you specify both a ^ and a $, then you're looking to match the complete String to your regular expression.

The ^ and $ elements are known as "anchors" as they tie the start and/or the end of the String down; this group as a whole is also known as "assertions" because they don't match any specific characters in the incoming string, they just assert that while the match is running a certain condition must occur at the given point in the match.


If you write

[abcdef]


in your regular expression, then you're matching any one character from the list given (a b c d e or f). You can expand this capability further by using a minus sign to specify a character range, thus

[a-z]
any lower case letter
[0-9a-fA-F]
any hexadecimal character


and if you want to match any character except one from a list, you can start the character list with an ^ character, for example:

[^a-z]
any character except a lower case letter
[^%0-9]
any character except a digit or a % character

but that would get messy really fast, so there are some common groupings available in Java's regular expressions:

\s
any white space character
\d
any digit
\w
any word character (letter, digit, underscore)


If you want any character except one of these, use a capital letter:

\S
any character that is not a white space
\D
any character that is not a digit
\W
any character that is not a word character


Sequences such as \s will be familiar to you if you use Perl's regular expressions, but there are other character groups too; these use a POSIX standard definition of the character groups, but it's extended and the format isn't taken from Perl, nor PHP, nor Tcl nor SQL!

\p{Space}
Alternative to \s for "any white space"
\p{Blank}
Space or tab character
\p{Alpha}
Any letter (upper or lower case)
\p{Graph}
Any visible character
\p{InGreek}
Any Greek letter
\p{Sc}
A currency symbol


You can negate these groups using \P rather than \p thus

\P{Graph}
Any character that is not visible


One final grouping, the ultimate group if you like, is the "." (full stop or period) character, which matches virtually any character.


COUNTS


The fourth main group (after anchors, literal characters, and character groups) are the counts; you use these in regular expressions if you want to give a quantity to a literal character or group, and you add the count character into you pattern directly after the element to which it applies. There are three very common counts:

+
one or more
*
zero or more
?
zero or one

Source: http://www.wellho.net/solutions/java-regular-expressions-in-java.html

Fun exploring new things. :)

Tuesday, May 6, 2008

Spring Batch Update Code

Code snippet to execute batch operations using spring

Collection vBatchUtilitySlotModelCollection = batchSlotUtilityBusinessService.getCollection();
if(vBatchUtilitySlotModelCollection != null && vBatchUtilitySlotModelCollection.size()>0)
{
BatchSqlUpdate batchUpdater = new BatchSqlUpdate(getDataSource(),"UPDATE slot SET location_seq_num = ?, facility_seq_num = ? WHERE seq_num = ?");
batchUpdater.declareParameter(new SqlParameter(Types.BIGINT));
batchUpdater.declareParameter(new SqlParameter(Types.BIGINT));
batchUpdater.declareParameter(new SqlParameter(Types.BIGINT));
batchUpdater.compile();

for (Iterator iter = vBatchUtilitySlotModelCollection.iterator(); iter.hasNext(); ) {
VBatchUtilitySlotModel vBatchUtilitySlotModel = (VBatchUtilitySlotModel)iter.next();
batchUpdater.update(new Object[] {vBatchUtilitySlotModel.getLocationSeqNum(), vBatchUtilitySlotModel.getFacilitySeqNum(), vBatchUtilitySlotModel.getSeqNum()});
}
batchUpdater.flush();
}

It worked like a flash..!!!!

-Happy Coding
--Sunny

Friday, May 2, 2008

Singleton across JVM's

When you make an Object singleton, we all know its just unique per jvm or per class loader.

So what if you want to make an object unique in a clustered environment. One way of doing it is using JNDI object binding. Here is some sample code try to run on ur server.

private void jndiObjTest(){

try{
System.out.println("Teting jndi object cache");

NotchClient nc=new NotchClient("Sunny","T");

Hashtable ht = new Hashtable();
ht.put(Context.PROVIDER_URL, "http://localhost:7001");
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.REFERRAL,"throw");
InitialContext ctx = new InitialContext(ht);
ctx.bind("sam_name",nc);

System.out.println("Reading Object from JNDI lookup");
Object o=ctx.lookup("sam_name");

NotchClient n=(NotchClient)o;
System.out.println("Value of obj retrieved from jndi"+n.getName());

}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
Note: Please deploy the above code to ur local server to test, standalone java app wont work.

--Sunny

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

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..!!!