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.