Wednesday, July 30, 2008

Navigation Code in JavaFX

So finally I am able to write a small code with the new Java FX API and Builder provided in NB 6.1. I have also seen one bug got fixed (maybe initially it was handled on a different way). Initially when we make any FX project in Netbeans, it basically store the *.fx code into classes folder as well. There is no way one can find the .class file of the .fx file, which is not a problem now.

I have written one small navigation code of map from key control. Which moves the map left, right, up and down from the corresponding key. And the most part of the code line is to handle the boundary condition like the image should not move left when it is already in left most region and so on. Thanks to Vikram for helping me out in writing boundary condition, this is always confusing for me :-D. Here is the small code:

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.paint.Color;
import javafx.input.KeyEvent;
import javafx.input.KeyCode;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.input.MouseEvent;
import javafx.scene.transform.Translate;
import java.lang.*;
import javafx.scene.geometry.Line;

var x1 : Number = 0;
var y1 : Number = 0;
//var myImage = Image { url: "{__DIR__}/./earth-map-big.jpg" };
var myImage = Image { url: "http://arstechnica.com/reviews/4q00/macosx-pb1/images/earth-map-big.jpg" };
var line: Line;

Frame {
title: "MyApplication"
width: 500
height: 500
resizable: false

closeAction: function() {
java.lang.System.exit( 0 );
}
visible: true
stage: Stage {
fill:Color.BLACK
content: [
ImageView {
image : myImage
transform : [
Translate { x : bind x1, y : bind y1 }
]
onKeyPressed: function( e: KeyEvent ):Void {
System.out.println(x1 + " " + y1);
if(
e.getKeyText() == "Left")
{
if(x1 < 0) {
System.out.println(x1);
x1+=50;
}
}
if(
e.getKeyText() == "Right")
{
if(Math.abs(x1 - 500) < myImage.width) {
System.out.println(x1);
x1-=50;
}
}
if(
e.getKeyText() == "Down")
{
if(Math.abs(y1 - 500) < myImage.height) {
System.out.println(y1);
y1-=50;
}
}
if(e.getKeyText() == "Up")
{
if(y1 < 0) {
System.out.println(y1);
y1+=50;
}
}
}
opacity:1
}
]
}
}

I am loading the image from URL itself, so it will take sometime(because Image size is 3200 X 1600). Rest all is mathematics :-). Still lot more fancy job to do !

Original Post




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.