Friday, May 16, 2008

Taking input into batch file(sh file) from Java code

Most of the time when we start server, we write lot of code to optimize the condition. Most of those things are tough to write in Java but easy for batch file or sh file to work on. Like, go into a folder, set JAVA_HOME, setting some heap size and then fire the server. Things are not always start forward, sometime we need to pass some message or some path or some value from Java code to batch file.

Here I tried to write one. Say my JAVA_HOME is dynamic and on some condition I decide what's going to be JAVA_HOME and further on that what java and javac going to run(means setting path).

import java.io.*;
public class batchCheck {
public static void main(String[] args) {
//All JavaHomes
String javaHome[] = {"E:\\Program Files\\Java\\j2sdk1.4.2_05", "E:\\Program Files\\Java\\jdk1.6.0"};
String path;
String line = "";
String pathFile = "E:\\Program Files\\Java\\jdk1.6.0\\bin\\JavaOutput";
String whichJDK = "";
String decisionMaker = "142";
if (decisionMaker.equals("142")) {
whichJDK = javaHome[0];
} else {
whichJDK = javaHome[1];
}
try {
path = whichJDK + "\\bin";
String cmds[] = {"check.bat", pathFile, whichJDK, path};
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmds);
proc.getOutputStream().close();
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Now, you can see my check.bat file:

cd %1
DEL HelloWorld.class
set PATH=%3
set JAVA_HOME=%2
echo %JAVA_HOME%
javac HelloWorld.java
java HelloWorld
exit

So, see how we can access the values from java file into batch file from %1, %2, %3 ... ($1,$2... in sh). Simply I moved on to the path where HelloWorld.java resides. I have deleted the old class file and the set the path, set the JAVA_HOME, compiled with javac of new JAVA_HOME and ran the code + exit :D.

Lot many things have been done from a very simple code.

Monday, May 12, 2008

Nimbus Look And Feel !

Good news for all the user, using JDK6. Though I am little late in writing blog on this but its OK ;). JDK6 current update comes with a new L&F(Look And Feel) called Nimbus.

Nimbus provide more lively look and feel in Swing UI. Here are some examples:

Default Look And Feel(Click to see enlarged mode)
Nimbus Look And Feel((Click to see enlarged mode)

Since the image is little small and related to my Online Java Project(which I can't change), so I provide another example here from my last blog code.

Default Look And Feel
Nimbus Look And Feel
Something more interesting is focus traversal on components. For Default L&F, you can see that there is a dotted rectangle on Button 3, which says "Focus is here" whereas in Nimbus you can see Button 1 with little bluish highlight which says "Look at my focus" :)

Quickest way to try, command line:

Run my previous (or any UI code) with the following option:

java -Dswing.defaultlaf=com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel LayoutCheck

Off course, you can do it with code :
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
Use try, catch and respect Exception handling as well.

Sunday, May 11, 2008

Layout use in Java

Setting the right layout is one of the major concerns in Java Programming. Swing Package provides number of classes and API's for setting border and layout but using the right one will make our UI lively and error free. First of all, when we are worrying about Layout just worry for Panel and content Panes nothing else.
Now here we will check some of the common Layout style and difference between them. Default Layout for JPanel is FlowLayout but what I use most commonly is GridLayout and BorderLayout. Lets first talk about the grid layout. Here is a simple code:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class LayoutCheck extends JPanel {

public LayoutCheck() {
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
add(button1);
add(button2);
add(button3);
add(button4);

setLayout(new GridLayout(2, 2));
setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED), "All Buttons"));
}
public static void main(String[] args) {
LayoutCheck lc = new LayoutCheck();
JFrame frame = new JFrame("Checking Layouts");
frame.setContentPane(lc);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
}

So, 4 buttons with grid layout of 2 X 2. Output will be definitely like this:



Playing on these 2 lines will tell us more:

setLayout(new GridLayout(2, 2));
setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED), "All Buttons"));

is place of (2,2) if we do (4,1) or (1,4) it will give vertical and horizontal look. What if we want to put some gaps in between the buttons. We need to use:

setLayout(new GridLayout(2, 2, 5, 5));

It will provide horizontal and vertical gap of 5. Second line in code is setting the recgaular box around the buttons "All Buttons". There are some options in EtcherBorder, please check the API page for more detail.

GridLayout divides the whole panel into grid, so maximizing or minimizing will going to increase or decrease the size of button, unlike other layout.

From Sun Java Document, I am just copying that in which case which layout need to be used. Follow this religiously, we can make a rich UI based application:

Scenario: You need to display a component in as much space as it can get. If it is the only component in its container, use GridLayout or BorderLayout. Otherwise, BorderLayout or GridBagLayout might be a good match. If you use BorderLayout, you will need to put the space-hungry component in the center. With GridBagLayout, you will need to set the constraints for the component so that fill=GridBagConstraints.BOTH. Another possibility is to use BoxLayout, making the space-hungry component specify very large preferred and maximum sizes.

Scenario: You need to display a few components in a compact row at their natural size. Consider using a JPanel to group the components and using either the JPanel's default FlowLayout manager or the BoxLayout manager. SpringLayout is also good for this.

Scenario: You need to display a few components of the same size in rows and columns. GridLayout is perfect for this.

Scenario: You need to display a few components in a row or column, possibly with varying amounts of space between them, custom alignment, or custom component sizes. BoxLayout is perfect for this.

Scenario: You need to display aligned columns, as in a form-like interface where a column of labels is used to describe text fields in an adjacent column. SpringLayout is a natural choice for this. The SpringUtilities class used by several Tutorial examples defines a makeCompactGrid method that lets you easily align multiple rows and columns of components.

Scenario: You have a complex layout with many components. Consider either using a very flexible layout manager such as GridBagLayout or SpringLayout, or grouping the components into one or more JPanels to simplify layout. If you take the latter approach, each JPanel might use a different layout manager.

We will talk about some of the common scenario in our next blog session.

Thursday, May 08, 2008

Filter file(s) in JFileChooser

JFileChooser is one of the most important components when we talk about Swing application from small to big size applications. Most of the time we write the code of JFileChooser on a button listener aka open a file on button name Open, so code will go :

open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int returnVal = fc.showOpenDialog(FileChooserFrame);
//do action according to the value of returnVal
................

But its always better to put a filter on a specific type of file which is required. Most of the time user don't required all types of files. Say, he need only .avi files or .mov files. Thens its a good idea to put a filter which will give only .avi or .mov files in the file chooser option. Month back, I had written one small code which do filtering for .java and .sh files and here it is:

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;

class JtregFilter extends FileFilter {

public boolean accept(File f) {
if (f.isDirectory())
return true;
String s = f.getName();
int i = s.lastIndexOf('.');

if (i > 0 && i < s.length() - 1)
if (s.substring(i + 1).toLowerCase().equals("java" ) || s.substring(i + 1).toLowerCase().equals("sh" ))
return true;

return false;
}

public String getDescription() {
return "*.java, *.sh";
}
}

Now nothing need to do in listener except adding one more line :

open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
fc.addChoosableFileFilter(new JtregFilter());
int returnVal = fc.showOpenDialog(FileChooserFrame);
//do action according to the value of returnVal
...................

and we are done. Now JFileChooser will only show me folders and file with extension .java or .sh. Worthwhile to write a small code for user ease.

Tuesday, April 29, 2008

Compiler Optimization Can cause problem

Last week, I was created a presentation on Multi-threading in Java. Though this fact, I have covered in presentation but still wanted to blog on same. In multi-threading world, compiler optimization can cause serious problems. Just check my small code:

public class NonVolatileProblem extends Thread{

ChangeFlag cf;

public static void main(String[] args) {
ChangeFlag cf = new ChangeFlag();
NonVolatileProblem th1 = new NonVolatileProblem(cf);
NonVolatileProblem th2 = new NonVolatileProblem(cf);

th1.start();
th2.start();

}
public void run() {
cf.method1();
cf.method2();
}

public NonVolatileProblem(ChangeFlag cf) {
this.cf = cf;
}
}

class ChangeFlag {

boolean flag = false;

public void method1() {
flag = false;
try {
Thread.sleep(1000);
} catch(Exception e) { System.out.println("Don't want to be here"); }
if(flag) {
System.out.println("This can be reached ");
}
System.out.println("Value of flag" + flag);
}

public void method2() {
flag = true;
}
}

Check out the reason in bold. Now if compiler optimize the code and remove the part of if(flag), thinking of that flag value will always be false. Then we have a situation here(FBI style of speaking :-D), because other thread can change its value and can make the flag value true. Just run this code 5-6 may be 10 times, you will be able to see the SOP statement "This can be reached". Just for the shake of getting that I have added sleep statement. Here what I got on my 3rd run of the code :)

Value of flag:false
This can be reached
Value of flag:true

Handling such type of situation is not difficult, specification says to add a word volatile before the variable flag which will tell the compiler not to optimize its code just by seeing some initial value or declaration.

Sunday, April 27, 2008

Atomic Operations in Java

Knowing atomic operation is very important when we are writing thread operation. Covering atomic operation inside synchronized keyword is just a overhead which we discussed sometime back in one post. Now

what all comes under atomic operation:

1. a = a + 1 - certainly not. Because this operation can use a local variable or a register to store the information before assigning it back to a. This operation is more or less like:

temp = a+1;
a = temp;

Certainly, reading value of a in between the two operation will create a dirty read.

2. a = b; Is this a atomic operation ? It depends ! Java Specification says that assignment to variables smaller than or equal to 32 bits is an atomic operation, which excludes variables of types double and long

(both are 64 bits). So, the operation is atomic or not completely depends on type of a and b. Now, reason behind such a specification is very clear, any operation more than 32 bit should need a extra

storage(basically register) for a 32 bit processor. But here Java Spec is not speaking about any processor dependency. Now, I am surprised how VM will handle atomicity if ran on 16 bit processor. I don't know

but I guess we can run JVM on 16 bit processor. Is it handles atomicity internally ? How about 64 bit processor. Even double and long operation should be atomic.

I am confused :-(

Friday, April 25, 2008

Online Java Output !

Again one idea, implementation of which I am not able to find on internet. Most of the time for testing purpose we need to run small piece of codes basically the non-UI code. And we do it a lot when we prepare for certification exams like SCJP or SCJA. Some small tricky questions ! Not only this most of the time JDK version matters because one can't run generics code with JDK 1.4 backwards.

Why not to make a small web based tool, which takes the java file as an input from user and give option to user to select which JDK version is required probably by radio button(radio button is a nice name, its like radio in which you can select only one station at a time, I wonder why not television button :-) ) and we show the output of that java file on a JSP page or we can also write it somewhere on a file, as user demand, after all user is God :-). For UI code, it will simple return a message like its a UI code and cant be displayed.

So, implementation is little like JFileChooser for selecting input file and for writing output file. Radio buttons for selection of JDK and thats it ! Rest my web server will take load of all JDK version and it will be the duty of code to run the java file on the appropriate JDK version.

Please give your useful comment on idea and also if there is anything exist like this. I would love to use it rather than writing :-).

Thursday, April 24, 2008

Java - No Pass by Reference

Back to Basics :)

I still see some of my friends get confused with Pass by Reference in Java. Only point to note, there is no pass by reference in Java, we only have pass by Value and sometime we pass the object reference by Value(that doesn't mean pass by Reference).
Year back I had a big discussion on my Orkut community about this and I am again posting the same code for clearing the confusion.

class MyClass {
String name;
int nameCode;

public MyClass(String name, int nameCode) {
this.name = name;
this.nameCode = nameCode;
}
public String toString() {
System.out.println(name + " : " + nameCode);
return(name+nameCode);
}
}
public class NoCallByReference {
public static void swap(MyClass a, MyClass b) {
MyClass temp = a;
a = b;
b = temp;
}
public static void main(String[] args) {
MyClass myclass = new MyClass("Ramu", 7);
MyClass yourclass = new MyClass("Mohan", 1);
swap(myclass, yourclass);
myclass.toString();
yourclass.toString();
}
}


A very simple code where I tried to swap two object of myClass. But you will surprise to see the output because after swapping even the value of myclass and yourclass will remain the same. Because the copy of myclass and yourclass has been created and get swapped rather than actual myclass and yourclass. It's like

myclass --- copyofmyclass
yourclass --- copyofyourclass


Swapping is done on copyofmyclass and copyofyourclass. Better to go for a homework and run the command

javap -c NoCallByReference and try to figure our how assemble is going on :-).

For more details and hot talk check the orkut link here.

Friday, April 18, 2008

Review of uCertify

Long time, no blogging ! But I am back :-).

Last month I got the honor to review some of the packages of uCertify. A very nice site to prepare for Java certification. I have reviewed SCJP 5 Package questions.

- The Great part: The questions stand on right level of difficulty and match with the standards of the actual certification exams. It has been more than 2 years since I gave my SCJP exam. And I find the uCertify questions analogous to the main exam, neither easy nor too tough.

- I have seen lot of questions covering new topics like autoboxing, new FOR loop, Generics and many more. Good stress is made on threading questions because this is the one area where you need to apply logic directly in the exam.

- Navigation of the questions was a little difficult. In the main exam, the questions numbers are displayed like an index on the top, you could just click and go to a particular question.

- Explanation of answers is good. I feel there is some scope for improvement. My personal opinion: practical examples will make us comfortable + are quick to understand.

- Here goes the tagging, I love it ! You can assign your own tag for questions and then you can make a customized paper from those tags. Weaker part, more practice :)

Ah good recap of my exam days. I feel like giving the certification exam again :-) I am again very thankful to sites like uCertify and Whizlabs which provide a good deal of questions and make the life little easier for aspirants

Tuesday, April 08, 2008

Image to Polygon

Java 3D and Java 2D image package is now strong enough to do any job. Weeks back I was looking at the morphing support by JavaFX, which is quite awesome. But I want to morph the images not shapes. Morphing an image is possible because Image in nothing a mixture of lot of shapes(at least mathematically :) ). So, I have decided to start working for Morphing of Images like Tiger getting converted into Man or Car getting converted into Horse. The basic idea is we need to convert Images into its Polygon form. First concentrating on 2D images(how funny, images are only 2D). 3D conversion is no doubt a tough job but do-able in Java, which demands for high efficient algorithms.

So, the basic need is to convert a 2D image into connected dots which can tell me something about shape. Looking those dots, I can guess this is a dog skeleton. I have seen some of 3D effort on net:

http://make3d.stanford.edu/
http://www.cs.uiuc.edu/homes/dhoiem/projects/popup/index.html

But how about making a cool polygon-ization in Java :). Raising same question on Java Developer site leads me to the conclusion that we can go ahead and do this work. I will post more details on this as the work will progress.

Thursday, March 13, 2008

How many JRE on my Windows machine

Today we are doing some discussion on JRE and one of my friends Lawrence asked me a question "How to find how many JRE are installed on system by Java Code ? " Now I don't think Java have any such API which will tell how many JRE are installed on System and what are they ? But my another friend Vikram has a saying that JRE installation write information in Registry. And here I tried to write this code. It will only run on Windows :) because again I have used Runtime class. I would love to know how the same could be achieved in Unix Systems. This code is not doing anything, just do query from registry and reflects the answer on the console.

import java.io.*;
class NoofJRE {
static String REG_PATH = "reg query " +
"\"HKLM\\Software\\JavaSoft\\Java Runtime Environment";

public static void getJREInfo() {
try {
Process process = Runtime.getRuntime().exec(REG_PATH);
InputStream inputstream = process.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
}
catch (Exception e) {
System.out.println("I am in Exception");
}
}
public static void main(String s[]) {
getJREInfo();
}
}

And here is my output:

E:\Program Files\Java\jdk1.6.0\bin>java NoofJRE
! REG.EXE VERSION 3.0
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment
CurrentVersion REG_SZ 1.6
BrowserJavaVersion REG_SZ 1.6.0_01
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.4.2_17
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.6
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.6.0
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.6.0_01

Which sounds true in my case. It is clearly telling me that I have JRE 1.4.2_17, 1.6.0 and 1.6.0_01. I have old bad habit on not uninstalling JRE's :). Please let me know if there is any other way to know how many and which JRE is/are installed in my system.

And to know where it is installed is also easy by querying JAVA_HOME in registry value.


Monday, March 03, 2008

Listing Java Process from Java

Month Ago, one of my colleagues was making an application, actually the UI flavor of JStack. Since JStack asks you the process ID for attaching the particular Java Application with JStack. In a UI based tool, telling user to do Alt-Ctrl-Del and see the process ID,not sounds good. So, my first impression was that you have to show the java process in the drop down and user will select in that. Some day back even, I want to find all process running on my machine from java code for some stupid purpose. I am trying to write some code for both of them. Java can't play with system process and hence invoking a runtime is only solution to get all process and here it is:


import java.io.*;
class ListProcess {
public static void main(String[] args)throws IOException
{
Runtime runtime = Runtime.getRuntime();
String cmds[] = {"cmd", "/c", "tasklist"};
Process proc = runtime.exec(cmds);
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
}
}


Code is written exclusively for Windows Machine :). And one line change in this code will list you only java running process.

String cmds[] = {"cmd", "/c", "jps"}; this is nothing but running jps.exe file in bin (jdk6 onwards). Its not all done. Writing Runtime code is not the real solution as there is little of platform dependencies. So, I have decide to write the code for getting List of Java Process. Again, I have checked by OpenJDK code for jps(search on jps.java file :) ) and I got some hint how to do it and here it goes:

import java.util.*;
import sun.jvmstat.monitor.*;

public class ListJavaProcess {
public static void main(String[] args) throws Exception {

/* Checking for local Host, one can do for remote machine as well */
MonitoredHost local = MonitoredHost.getMonitoredHost("localhost");
/* Take all active VM's on Host, LocalHost here */
Set ids = new HashSet(local.activeVms());
for (Object id : ids) {
/* 1234 - Specifies the Java Virtual Machine identified by lvmid 1234 on an unnamed host.
This string is transformed into the absolute form //1234, which must be resolved against
a HostIdentifier. */
MonitoredVm vm = local.getMonitoredVm(new VmIdentifier("//" + id));
/* take care of class file and jar file both */
String processname = MonitoredVmUtil.mainClass(vm, true);
System.out.println(id + " ------> " + processname);
}
}
}


I have written good amount of comment as it is all together a sun import rather than java or javax import(so no javadoc). This import resides in tools.jar, so even running simple javac and java will not work. So, running the program will go here:


E:\Program Files\Java\jdk1.6.0_10\bin>javac -classpath "E:\Program Files\Java\jd
k1.6.0_10\lib\tools.jar" ListJavaProcess.java


E:\Program Files\Java\jdk1.6.0_10\bin>java -classpath .;"E:\Program Files\Java\j
dk1.6.0_10\lib\tools.jar" Vista

3700 ------> ListJavaProcess

Right now only one java process is running. Now in the second code, you can play with some of the java process, but with native process in the above code you can't do anything except watching it :)

Monday, February 18, 2008

Play Safe with Swing

Last month, I was writing a GUI based code in Java. As Swing provides rich UI so I decided to go for Swing. Here is a simple piece of Suggestion, which most of us know already. If you are a novice in Swing, you always need to take care in calling UI work. Reason is simple, swing is not thread-safe and calling GUI work randomly will lead to a deadlock in code. We are seeing 'n' no. of problem with Swing code, just because developers don't know(or maybe forget) that swing is not a thread-safe world. Sometime you are not able to see the problem initially but afterward when your code is going heavier and heavier you will face lot of problems.

How to make Swing Thread-safe ?

Its not a tough job. First see this, this is more or less like a rule and you can apply anywhere to write a safe code:

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.show();
// Anything after this is going to be crappy and thread unsafe
}

If you are going to write two UI work, and since things are not synchronized, you can go into a big mess. I wanted to post my code where I got the problem some days back, but its too big to post. No worries I got a code from here which is amazing ! You know what is cool, it crashes every time :)

import javax.swing.*;
import java.awt.*;

public class StrangeProblem extends JFrame {
static {
new StrangeProblem();
}

private static void staticMethod() {
System.out.println("This is never reached");
}

private StrangeProblem() {
getContentPane().add(new MyJDesktopPane());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
// If commented out, program works fine, otherwise it hangs
new JInternalFrame();
}

private class MyJDesktopPane extends JDesktopPane {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("We will now call the static method...");
staticMethod();
System.out.println("Static method was called.");
}
}

public static void main(String[] args) {
}
}

(Thanks for the poster of this code)



So now you got the thumb rule, what not to do ! Alright time to see what to do.

Simple. Run your code in the event-dispatching thread. Most of the UI like event, mouse clicks are always handled by event-dispatching thread. SwingUtilities class provide two methods invokeLater() and invokeAndWait() to get rid of this problem. Now, why two different methods is a big mystery, but use invokeLater() if its a case of Swing. So, now the code skeleton is :

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();
f.show();
// you can write more UI work here
}
});
}

I can leave it on to you to make the above code deadlock free :). For more detail, see the SwingUtilities class JavaDoc.

Saturday, February 09, 2008

Sorting with Different Locale

Sorting is always a tricky game in any language. Language like Java has its own high class sorting API's. But have you ever think, how sorting works in different locales ? How it work in French or in Spanish? Lets have a look...

This is my String Array which I want to sort:
String[] names = {"fácil", "facil", "fast","Où", "êtes-vous", "spécifique", "specific", "ou"};
It contains words of French Locale(some of my fav. words like Où :-) )
And here goes our typical sorting program:

String[] names = {"fácil", "facil", "fast","Où", "êtes-vous", "spécifique", "specific", "ou"};
List list = Arrays.asList(names);
Collections.sort(list);
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.print(itr.next()+ " ");
}

And the result:
Où facil fast fácil ou specific spécifique êtes-vous

Result can surprise you and can make your French friend angry :-) because he never want "fast" should come before "fácil", just because there is one special 'á' (sorting is true according to UNICODE sequence but not according to locale)

To face this problem JDK comes with something called Collator (I guess in 1.4 onwards) which take care of locale while sorting.
Collator is an abstract class. You can look the source code at location in Openjdk: jdk\src\share\classes\java\text\Collator.java. Highly documented file.

Collator has some flavors like PRIMARY, SECONDARY, TERTIARY, IDENTICAL which all tells what need to take care while sorting. Please read the javadoc for detail.

Now here is my simple code:

import java.text.*;
import java.util.*;


class CollatorTest {

public static void main(String[] args) {
String[] names = {"fácil", "facil", "fast","Où", "êtes-vous", "spécifique", "specific", "ou"};
List list = Arrays.asList(names);
Collections.sort(list);
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.print(itr.next()+ " ");
}

Locale[] loc = Collator.getAvailableLocales();

/* for(int i=0;
&<
{
System.out.println(loc[i].getDisplayName());
}
*/
Collator myCollator = Collator.getInstance(new Locale("fr"));
myCollator.setStrength(Collator.PRIMARY);
Collections.sort(list, myCollator);
itr = list.iterator();
System.out.println("");
while(itr.hasNext()) {
System.out.print(itr.next() + " ");
}

myCollator.setStrength(Collator.TERTIARY);
Collections.sort(list, myCollator);
itr = list.iterator();
System.out.println("");
while(itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}

And here is the result:
Où facil fast fácil ou specific spécifique êtes-vous
êtes-vous facil fácil fast Où ou specific spécifique
êtes-vous facil fácil fast ou Où specific spécifique

First one is the normal sorting, second and third is Collator sorting with 2 different types. You can very easily see that we are giving respect to other locale as well in sorting. There are 2-3 line comments in the code, which will tell which all locale Collator is supporting.

Sunday, January 13, 2008

MyClassLoader - Java ClassLoader Final Part

Sorry as I am not able to proceed sequentially. But now its time for implementation. I have 3 java files with me:

1. myClassLoader.java which inherits from ClassLoader and implements the minimum requirement.

2. myClassLoaderMain.java which loads the class HelloWorld, making its instance and calling one of the method of it.

3. HelloWorld.java which is simply a program with one method.

myClassLoader is not doing any of the special job but at the end I am providing you the link of some more documents which can provide you special classLoader like one good article is showing you how to load class change on fly.

myClassLoader.java

import java.io.*;
import java.util.*;
public class myClassLoader extends ClassLoader {
private Hashtable classes = new Hashtable();
public myClassLoader(){
super(myClassLoader.class.getClassLoader());
}
public Class loadClass(String className) throws ClassNotFoundException {
return findClass(className);
}

public Class findClass(String className){
Class result=null;
result = (Class)classes.get(className);
System.out.println("Class Name is : " + className);
if(result != null){
return result;
}
try{
return findSystemClass(className);
}catch(Exception e){
return null;
}
}
}

myClassLoaderMain.java

public class myClassLoaderMain {
public static void main(String [] args) throws Exception{
myClassLoader test = new myClassLoader();
Object o = (test.loadClass("HelloWorld")).newInstance();
((HelloWorld)o).mymethod();
}
}

HelloWorld.java

class HelloWorld {
public void mymethod()
{
System.out.println("Atleast print this ");
}
public static void main(String[] args)
{
System.out.println("Hello World");
}
}

Now running all together:

javac *.java
java myMainClassLoader
/* It will call mymethod of HelloWorld */

If you are keen to move further and want to make some magical class Loader please check this articles:
1. Basics of ClassLoader on JavaWorld.
2. A look at Java ClassLoader - Here they made an example of loading class at runtime.
3. Java ClassLoader wiki page.

Any comments or correction or questions are most welcome.

Inheritance and Memory Retention Issue with Finalization

Finalization is mostly used in Java to reclaim resources, native resources. Say, you are writing one program and you are using Windows Font(OS font). So, its the programmers duty to reclaim the font resource associated with any object.

If you are an application developer and uses lot of native resource then I would say stop reading this blog and read the latest Article(yes, Sep 2007) by Tony Printezis on sun site. This article is awesome and covers all the cases and its solution that can happen with Memory Retention. The simplest of that is what I am going to talk here.

Now, consider an example :

class PlayWithFont {

String someText;
String newText;

private native method getFont();
void get() { getFont(); }

// private because its a native method and always be called by any method of this class only
private native method releaseFont();
void release() { releaseFont(); }
protected void finalize() { release(); }

}

Now, here I have some text and I am taking OS font, converting that text into some fancy text and then releasing the resource of Operating Systems.
We have a class called PlayMoreWithFont which basically inherits PlayWithFont and converting some String[] text into new String[] text (just a fictitious example)

class PlayMoreWithFont {

String[] someMoreText ; // lets consider it here some big chucks of memory
String[] newMoreText;

}

PlayMoreWithFont don't have any finalize method defined, but off course its going to take one from PlayWithFont.

GC maintain a finalization queue. When a object is unreachable, object is added to the finalization queue. After that only object goes into finalized state. Now when we called :

play = new PlayMoreWithFont;
play = null;

Now instance of PlayMoreWithFont become unreachable, but reclamation of big chunks like someMoreText and newMoreText has to wait until the instance is finalized. And this is one of the major causes of memory retention. Moreover the problem is difficult to find if the class hierarchy is very deep and finalize is sitting some where very deep.

There are some good solution which we can discuss in next.

Wednesday, January 02, 2008

MyClassLoader - Java ClassLoader - Part 2

MyClassLoader will take one more entry for completion. Before writing our own custom ClassLoader, we have to devote sometime to see the methods of ClassLoader. Some of them need special attention while others we can ignore. Before starting with methods, we can see some type of ClassLoader available in jdk(openjdk) itself. AppletClassLoader, RMIClassLoader, SecureClassLoader, URLClassLoader are some of them. Remember all the custom ClassLoader need to extend ClassLoader except one :-). Any guesses ? Bootstrap Class Loader - Yes, this is responsible for loading runtime classes(rt.jar- very famous jar file in /jre/lib :-) ) . It has a native implementation and hence varies across JVM. So, when we write

java MyProgram

Bootstrap ClassLoader comes into the action first.

Alright, back to methods: we can see the whole list of methods of ClassLoader here. But we will see those of our interest:

- loadClass -> entry point for ClassLoader. In JDK 1.1 or earlier, this is the only method we need to override but after JDK 1.2 some dynamics get changed. Will discuss that later.

- defineClass -> As I mentioned in the last blog, this is one of the complex method which takes raw data and turn it into Class Object. Need not to worry, it is defined as final(so we can't change... who want to change).

- findSystemClass -> looks for the class file in local disk, if yes calls defineClass and convert the raw data into Class Object.

In JDK 1.2, new delegation model came into picture where if ClassLoader can't able to find a class, it asks (it's) parent ClassLoader to do it. JDK 1.2 came up with a new method called findClass which contains specialized code and help you when you are messed up with lot of ClassLoader. So, from JDK 1.2 and onwards, we just need to override findClass and everything will work fine, if not it will throw ClassNotFoundException. There are lot of other methods like getParent, getSystemClassLoader, but we can write our custom ClassLoader without touching these methods.

So, top skeleton looks like:

public class MyClassLoader extends ClassLoader {

public CustomClassLoader(){
//getClassLoader returns ClassLoader
super(CustomClassLoader.class.getClassLoader());
}

}

//lot of thing after this

Tuesday, January 01, 2008

MyClassLoader - Java ClassLoader

I am very new to Java and often terms like ClassLoader, Virtual Machine scares me before start. With little of courage I start reading some of the documents on ClassLoader and ahh I find it very simple. Actually with reply to some of my old blog's comment, we had made a statement that "you can have your own classLoader in java".

The good part about ClassLoader - its written in Java :-). So one can expect code to be simple and more understandable than written in C++.

ClassLoader is nothing but a part of Java Virtual Machine responsible to load classes into memory. From where ? From local hard drive(mostly), from network and in some cases from browser. Little complex yet beautiful part of it is it load classes on demand not all at once. Java has an excellent feature to write your own classLoader which extends to ClassLoader class. Here, I named it as MyClassLoader :-). But if JVM has a classLoader why to write another one ? In my case, just for fun :D but there are other uses. One I got, is to automatically verify digital signature before invoking untrusted code. Second and more important when you want to update class at runtime. So, in this case we need to create another instance of our classLoader and then we can replace the already loaded classes with new updated classes. We can see some other usages as we move on to the blog.

I start reading some code here and there of classLoader from openjdk. If you have openjdk on your system, I will better suggest to go through some of the API implementation of ClassLoader. You will get the ClassLoader.java at path \jdk\src\share\classes\java\lang\ClassLoader.java. I was surprised to see that very less changes has been made to this file after jdk 1.2 and a great enhancement is done on jdk 1.2. In the code, you can see most of the API's have written in 1.2 only.

When java got released the most exciting and eye catching feature is how it execute code on the fly from remote server. Some kind of magic ? Yes, this magic is possible because java has the ability to write a custom classloader. The magic is this - in appletviewer/browser instead of looking into local had disk for classes it looks for remote server, loads the raw data through http and turns them into classes(duty of method called defineClass in ClassLoader, we will see this in more detail) inside Virtual Machine.

I am still in the midway of many document, reading re-reading and trying to understand more of it. We will try to see some of the method(s) which we need to implement for our custom ClassLoader, MyClassLoader. Most of the methods sounds easy but some methods like defineClass which is actually converting raw data into classes may go little complex.

Sunday, December 23, 2007

jhat - Java Heap Analysizer

Since I get involved in some jhat related project with one of my senior team members. I decided to make some blog entries. jhat is java heap analysis tool which is shipped in jdk6. There is an independent project name hat on hat.dev.java.net. jhat is flavor of this project only.

If you are a guy, who write lot of Java code and keep on looking for optimization, if you are getting errors like memory overflow.. then yes its a tools for you only.

jhat is all about giving readable information from java heap dump. Java Heap Dump contains information like how many classes, how many instances, execution flow and many more.
But all these information are in a binary format. And the duty of jhat is to read that file and provide useful information to you.

There are lot of ways to generate heap dump:

1. From normal java execution program, you can see the heap by Ctrl + Break.
2. jdk6,5 is coming with some tools like jmap, jconsole which help us to generate heap dump. Usages of these tools are very easy.
3. jdk5 also comes up with a tool called HPROF which can be used to generate heap dump.

So, here are the steps, how to approach the problem:

Make heap dump with jmap:

1. Run the java program, say SwingSet2 in the example.
2. Open other terminal, and run jmap
jmap -dump:format=b,file=heap.bin (On Windows, you can get pid by Ctrl-Alt-Del -> Process -> PID )

jmap will generate a file with name heap.bin which contains heap dump. Now pass this heap.bin to jhat.

3. jhat heap.bin

There are lot many optional argument, check the detail here.

Open browser, type: http://localhost:7000 (7000 is the default port), you can see hell lot of information. Grab the information of your interest. Or if you want to parse the information from yourself use OQL(Object Query Language) and write query.

Sunday, December 09, 2007

How Java handles Method ?

In my previous blog "Performance - Final Keyword ? " One of the blog readers asked question about How Java handles overriding ! So, I decided to make one entry(I guess more than one) for the answer.

Yes overriding tactics in Java is very different from C++ as methods by default in Java can be overridden unlike C++. In C++, the concept of overriding functions are handled by Virtual Table, VTable(This wiki link contains lot of information). Whereas in Java there is some other concept. Before going into the depth, let's see some of the basic things which one should need to know before making hand dirty in overriding concept.

Here is a Simple HelloWorld Program:

class Hello {
public static void main(String[] args)
{
System.out.println("Hello Bloggers!");
}
}

Lets see what the bytecode is generating, javap -c Hello(more about javap)

Compiled from "Hello.java"
class Hello extends java.lang.Object{
Hello();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return

public static void main(java.lang.String[]);
Code:
0: new #2; //class Hello
3: dup
4: invokespecial #3; //Method "":()V
7: astore_1
8: getstatic #4; //Field java/lang/System.out:Ljava/io/PrintStream;
11: ldc #5; //String Hello it is
13: invokevirtual #6; //Method java/io/PrintStream.println:(Ljava/lang/Str
ing;)V
16: return

}

Have a look on these lines:

1: invokespecial #1; //Method java/lang/Object."":()V
4: invokespecial #3; //Method "":()V
13: invokevirtual #6; //Method java/io/PrintStream.println:(Ljava/lang/Str
ing;)V

These are the lines related to method invocation. So what the heck is this invokespecial and invokevirtual ? Actually JVM used 4 different kinds of instructions for method invocation those are :

- invokevirtual - This is for instance method like System.out.println("Hello Bloggers!") here.
- invokestatic - This is for class methods.
- invokespecial - This is for special things. It is used when
- call , instance initialization.
- super call, when you will call something from super.method
- private methods. As private methods can't be overridden so we need to put this in a special category.
- invokeinterface - invoking instance method with interface reference(Soon we will see the example)

Now we are very clear that why invokespecial has been used at #1 and #3 whereas invokevirtual at #6. Ok, lets write some code which can see the usages of all four.


interface interfaceForHello {
public void noUse();
}

class Hello implements interfaceForHello {
public void noUse() {
System.out.println("No use");
}
public static void staticMethod()
{
System.out.println("Static method");
}
public static void main(String[] args)
{
interfaceForHello iface = new Hello();
iface.noUse();
Hello.staticMethod();
System.out.println("Hello Bloggers ! ");
}
}

And here goes the javap -a Hello:

Compiled from "Hello.java"
class Hello extends java.lang.Object implements interfaceForHello{
Hello();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return

public void noUse();
Code:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3; //String No use
5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return

public static void staticMethod();
Code:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #5; //String Static method
5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return

public static void main(java.lang.String[]);
Code:
0: new #6; //class Hello
3: dup
4: invokespecial #7; //Method "":()V
7: astore_1
8: aload_1
9: invokeinterface #8, 1; //InterfaceMethod interfaceForHello.noUse:()V
14: invokestatic #9; //Method staticMethod:()V
17: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
20: ldc #10; //String Hello Bloggers !
22: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
25: return

}

In next blog we will continue the same.