Wednesday, July 30, 2008

Type Checking - Java, Fast !

Lots of our friends keep on asking, why to use Java SE 5.0 or Java SE 6. And most of the time you need to reply something impressive, then only they will start using it and can understand more benefits. I was reading the gradual performance improvement in JDK versions which is quite interesting. Java has spotted all its reason to being slow (very nice article, which speaks why Java is slow than C++) and optimized those on max level. One of the reasons mentioned in this article was Lots of Casts. And that's true, a good, big project code goes about millions of cast checking in Java and off course need attention for optimization. JDK 5 and onwards has done a fast subtype checking in Hotspot VM. This blog is dedicated on a small talk on the same, for detail read this article written by John and Cliff.

Prior to 5, Every Subtype has cached with its SuperType(casting of which is correct). The cache strength is 2 and if results return negative then its goes for a VM call which resolves this problem and caches if VM resolves it as positive. So anytime unavailability in cache is a costly operation where we need to make a call for VM. And in the worst scenario mentioned in SpecJBB we can have 3 rotating elements with 2 cache.

So, [A B] in cache <---- C found by VM and get cached, A is out now.

[B,C] in cache <-------- A negative test, VM call(+), get cached, B out.

[C,A] in cache <-------- B negative test, VM call(+), get cached, C out !

So, in basic term we can't trust on complexity(calls happen at runtime). And hence it better to move on a better algorithm. The new algorithm pass the code through an optimizer which checks more specification at compile time. Like if Base class and Derived class is known at compile time only. It try to understand lot of code at compile time only. It put the entire code inline and there is no requirement of VM calls. Complexity is quite consistent and it takes one load for most of the object or object array.

This also divide the subtype checks into primary and secondary checks. For Class, Array of Classes and for array of primitive value, primary check has been done whereas interface and array of interface are handled by secondary check. Finally a smart algorithm combines them.

In primary subtype check:

Aim to Check: Is S a subtype of T ? Calculate the depth of S and T. Depth mean to say all the parent. Though it is done in some base level or assemble level, I am writing a code in Java to find out the depth. Here is the code using reflection API's:

package findparent;
public class Main {

public static void main(String[] args) throws Exception {
String[] display = new String[10];
int i = 1;
FifthClass tc = new FifthClass();
Class classname = tc.getClass();
display[0] = classname.getName();
Class parent = classname.getSuperclass();
while (!(parent.getName().equals("java.lang.Object"))) {
display[i] = parent.getName();
classname = parent.newInstance().getClass();
parent = classname.getSuperclass();
i++;
}
display[i] = "java.lang.Object";
for (int j = 0; j <= i; j++) {
System.out.println(display[j]);
}
System.out.println("Depth of tc is " + i);
}
}

class FirstClass {
}

class SecondClass extends FirstClass {
}

class ThridClass extends SecondClass {
}

class ForthClass extends ThridClass {
}

class FifthClass extends ForthClass {
}


Now the algo. says:

S.is_subtype_of(T) :=
return (T.depth <= S.depth) ? (T==S.display[T.depth]) : false;

And further a lot of optimization. Which we will check in next blog :-). I will also try to cover how the secondary Subtype check is being done and also how to combine both the checks.

Till now, make a big inheritance tree and try to see the difference between older JDK and JDK5 onwards.

Small Java FX example

OK, nothing to laugh. I know my animation sense is little poor. But here I tried to move a ship, in the way they show in movies -D. Nothing like that, I have tried to give a sinusoidal movement of a ship. In the comment section, you can see there is a sea image as well. Animation was looking little ugly with sea, so I removed it :-). But point to note, you can give any animation to a image based on any mathematical methods. And if you have a complex equation, you can fit that in, in place of my simple sin curve. Here is the code:

package move;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.paint.Color;
import java.lang.Math;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;

var time : Number = 0.0;


var timeline : Timeline = Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames :
KeyFrame {
time : 5ms
action: function() {
time += 0.02;
}
}
};
Frame {
title: "MyApplication"
width: 1200
height: 500
closeAction: function() {
java.lang.System.exit( 0 );
}
visible: true

stage: Stage {
fill: Color.AQUA
content: [
/* ImageView {
image: Image {
url: "http://birdblog.merseyblogs.co.uk/sea21206.jpg"
}
},
*/
ImageView {
x:bind(100 + time * 10)
y:bind(100 + Math.cos(time) * 10)
image: Image {
url: "http://lal.cas.psu.edu/Research/visualiz/images/boat.gif"
}
}
]

}
}
timeline.start();


Just 3-4 drags from Netbeans 6.1 FX viewer :

1. One Timeline and an action inside it.

2. One Frame.

3. One Image.

Thats it ! Set the code logic and rest leave all the work on binding :-). Quite simple, just that I am not able to make some good animation out of it !

Originally posted on http://blogs.sun.com/vaibhav

Tuesday, July 15, 2008

JDK6 comparing with JDK1.4.2

Again a comparison and reason why JDK6. Weeks back one of our team member gave a presentation on JVM performance improvement in Mustang. I have just collected a useful point here and try to compare with older JDK version. Here is the code:

import java.util.*;

public class RuntimePerformanceGC {

public static void main(String[] args) {
RuntimePerformanceGC ob = new RuntimePerformanceGC();
Vector v = new Vector();
java.util.Date now = new java.util.Date();
long t1 = now.getTime();
ob.addItems(v);
java.util.Date now1 = new java.util.Date();
System.out.println(now1.getTime()-t1);
}
public void addItems(Vector v) {
for(int i =0;i<500000;i++)
v.add("Item" + i);
}
}

And the output in ms is:

JDK1.4.2: 984

JDK 6: 578

You can see a massive difference. 37 percent improvement in time. Why ? Here goes :

This is because of Runtime Performance Optimization. The new lock coarsening optimization technique implemented in hotspot eliminates the unlock and relock operations when a lock is released and then reacquired with no meaningful work done in between those operations. And this is what happening in our example. Since, Vector do thread safe operation, it takes the lock for add, release the lock and then takes it again.

So, I just tried to give one more reason why use JDK6 ;-). This is off course not the only reason for big improvement, I will try to cover some more in upcoming blogs :-)

JavaFX + Java

Tough to understand the code conversion :). I have seen the Java code of corresponding JavaFX code. Though its tough to map but we can see the correct correspondence. Let see this :

import javafx.ui.*;

Frame {
title: "Hello World JavaFX"
width: 200
content: Label {
text: "Hello World"
}
visible: true
}

and the corresponding Java Code:

import com.sun.javafx.runtime.Entry;
import com.sun.javafx.runtime.FXObject;
import com.sun.javafx.runtime.InitHelper;
import com.sun.javafx.runtime.Public;
import com.sun.javafx.runtime.Static;
import com.sun.javafx.runtime.location.AbstractVariable;
import com.sun.javafx.runtime.location.BooleanVariable;
import com.sun.javafx.runtime.location.DoubleVariable;
import com.sun.javafx.runtime.location.ObjectVariable;
import com.sun.javafx.runtime.sequence.Sequence;
import javafx.ui.Frame;
import javafx.ui.Frame.Intf;
import javafx.ui.Label;
import javafx.ui.Label.Intf;

public class Hello
implements Hello.Intf, FXObject
{
@Public
@Static
public static Object javafx$run$(Sequence paramSequence)
{
Frame localFrame = new Frame(true);
localFrame.get$title().setFromLiteral("Hello World JavaFX");
localFrame.get$width().setAsDoubleFromLiteral(200.0D);
Label localLabel = new Label(true);
localLabel.get$text().setFromLiteral("Hello World");

localLabel.initialize$(); localFrame.get$content().setFromLiteral(localLabel);

localFrame.get$visible().setAsBooleanFromLiteral(true);

localFrame.initialize$(); return localFrame; }
public void initialize$() { addTriggers$(this); userInit$(this); postInit$(this); InitHelper.finish(new AbstractVariable[0]); }
public static void addTriggers$(Hello.Intf paramIntf) { }
public Hello() { this(false); initialize$(); }
public static void userInit$(Hello.Intf paramIntf) { }
public static void postInit$(Hello.Intf paramIntf) { }
public static void main(String[] paramArrayOfString)
throws Throwable { Entry.start(Hello.class, paramArrayOfString);
}
}

This I have done by generating the class file and then de-compiled the class file.

Frame of JavaFX - Frame localFrame = new Frame(true);
title and text of JavaFX
- localFrame.get$title().setFromLiteral(”Hello World JavaFX”);
- localLabel.get$text().setFromLiteral(”Hello World”);

Visibility of JavaFX - localFrame.get$visible().setAsBooleanFromLiteral(true);

Lot of code is written to support JavaFX environment, which is completely justifiable. Don’t able to get why methods are written with $. If any clue, please let us know also.

Saturday, June 28, 2008

Performance Improvement in JDK6

Original Post: http://blogs.sun.com/vaibhav/entry/why_jdk6_again

Content:

Again a comparison and reason why JDK6. Weeks back one of our team member gave a presentation on JVM performance improvement in Mustang. I have just collected a useful point here and try to compare with older JDK version. Here is the code:



import java.util.*;
public class RuntimePerformanceGC {
public static void main(String[] args) {
RuntimePerformanceGC ob = new RuntimePerformanceGC();
Vector v = new Vector();
java.util.Date now = new java.util.Date();
long t1 = now.getTime();
ob.addItems(v);
java.util.Date now1 = new java.util.Date();
System.out.println(now1.getTime()-t1);
}
public void addItems(Vector v) {
for(int i =0;i<500000;i++)
v.add("Item" + i);
}
}

And the output in ms is:

JDK1.4.2: 984

JDK 6: 578

You can see a massive difference. 37 percent improvement in time. Why ? Here goes :

This is because of Runtime Performance Optimization. The new lock coarsening optimization technique implemented in hotspot eliminates the unlock and relock operations when a lock is released and then reacquired with no meaningful work done in between those operations. And this is what happening in our example. Since, Vector do thread safe operation, it takes the lock for add, release the lock and then takes it again.

So, I just tried to give one more reason why use JDK6 ;-). This is off course not the only reason for big improvement, I will try to cover some more in upcoming blogs :-)

Java 6u10 Features

Sorry for not writing for a long time. Actually I have start writing more on Sun Blog Site, so this blog space get affected . But today I got time to archive some of my blog work on this site.
Here is the latest :

Current work: Presentation in BOJUG meet. Download here. Don't forgot to give your comments :-). There are some demos which I try to cover in blog.

These slides basically talks about Java SE 6u10 features. Some of them are cool like

-> Next Generation Plugin where you can drap plugin outside the browser.

-> Kernel JRE. Download small JRE.

-> Nimbus Look And Feel

-> New Applet feature

Saturday, June 21, 2008

Disk Space Check

Take care of disk space when you are writing a big program :). Use JDK 6 features:

import java.io.File;

public class DiskSpaceCheck {
public DiskSpaceCheck() {
File file = new File("E:");
System.out.println("E:");
System.out.println("Total: " + file.getTotalSpace());
System.out.println("Free: " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());

file = new File("E://movie");
System.out.println("E://movie");
System.out.println("Total: " + file.getTotalSpace());
System.out.println("Free: " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());

file = new File("/");
System.out.println("n/");
System.out.println("Total: " + file.getTotalSpace());
System.out.println("Free: " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());
}

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

I was actually very suprised that why this feature came so late.

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.