JavaFX meets TaranFX.

JavaFX is built on top of a mature Runtime that gives developer’s amazing features. Java being in market since several years, they now have a more sophisticated API.

Update: This Blog post is Winner of Java Blogging Contest.

So what is JavaFX Hype all about?

I first got to hear about JavaFX more than a year back when I attended Sun Tech days. It wasn’t very mature at that time and failed to catch my attention. It was this year in Feb, when I saw a momentum and maturity in this platform, which encouraged me to take my steps further.

JavaFX gives developers an amazing feature-Rich API which will help them build scalable, fully integrated, Rich Graphics, Animated applications for the web. The beauty of JavaFX lies in the fact that its base (JVM) is already installed on all computers(90%).

When I first saw the API, I was amazed that it had so much pre-built into the API. e.g. All the common transitions like fading, scrolling, perspective animations are built-in. All you need is the idea and you can be all set to make the most powerful web application.

Being a Java at heart, you can always integrate it with existing java applications. Imagine a Live graphic Rich market-watch client talks directly to a EJB server to fetch live quotes and prepare animated graphs of statistical data and analytics to help you invest for future.

The feature I loved the most was, “applications are draggable to desktop”. Since apps run in JVM of local machine, though they open in browser, they can be dragged and dropped to desktop without interrupting any operation or performance.

Here is What I intend to Cover:

1. Example: How to Code Web Gallery in Javafx

i. Basic Overview

ii. The Code

a. Brief on animation Terminologies

b. Basic Code.

c. Transitions.

2. Benchmarking

i. Hardware used.

ii. Invocation and Startup

a. Observations

b. JavaFX vs. Flash

c. Conclusion

iii. Animated Transitions and Full Image load:

a. Key Observations

b. Conclusion

3. Verdict

i. Pros and Cons.

Let’s start with an example.

1. Example: How to Code Web Gallery in JavaFX

Before we start, you can have a Quick look at what we are going to achieve over here. It’s a decent web gallery inspired by one of them demoed on Javafx site. I took that gallery and re-wrote most of it to achieve the following:

1. Redesign UI to match my taste and site’s theme.

2. Optimize the code to max possible.

I did the latter to Benchmark JavaFX’s capabilities, as described in a later section. For now let’s look at the basics of JavaFX application design. Before we start, Let’s look at what did I make.

The Gallery is a JavaFX Frontend GUI with a backend supported by java Flickr API. On Load, Flickr is queried with REST API as http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&user_id=24847938@N07&api_key={apiKey}&per_page={thunbLayout.count}

HereI am sending request to Flickr to return me all public Photos for the user_id specified and per page show me {thunbLayout.count} many results per page using my unique API key.

This metaData when loaded, loads the 1st page of thumbnails. On selection via keyboard or mouse click on a pic, it opens for medium size and fizes the aspect ratio on load. While image is loaded, it is animated with Fade transition effect built into JavaFx. Let’s look at the code and things will get more clearer.

ii. The Code

Before we start, lets get you familiar with Jargons.

a. Basic Animation Terminologies:

Like Flash, JavaFX uses the generalized concept of Animations by using standard animation industry jargons. The First thing to learn is using Stages and Scenes. Stage is the main/core Placeholder for your JavaFX application. Scene is an independent widget which fits into Stage. Multiple Scenes can be put inside stage but there will be only one stage per application.

b. The Basic Code:

JavaFX made it really easy to code. Here is the code syntax:

[code lang=”javascript”]

var stage = Stage {

title: “Taranfx Gallery”

width: 840

height: 520

visible: false

style: StageStyle.TRANSPARENT

scene: bind scene

}

function run() {

initUI();

stage.visible = true;

// Set focus to background by default

bgRect.requestFocus();

}

[/code]

Here, run() Method is the default main method inside Main.fx class. So setting stage to visible, and getting the focus, does the job!

Now Let’s create scene for our thumbnails:

[code lang=”javascript”]

var scene : Scene = Scene {

width: 840

height: 520

content: Group {

content: bind stageContent //defined below inside initUI()

clip: Rectangle {

width: bind layout.width

height: bind layout.height

arcWidth: 20

arcHeight: 20

}

}

fill: Color.TRANSPARENT

}; [/code]

And Instantiate the UI components:

[code lang=”javascript”]

function initFrontUI() {

descTxt = Text {

x: bind layout.thumbX

y: bind layout.descTxtY

font: bind layout.descFont

wrappingWidth: bind (layout.thumbGroupW – 10)

content: bind description

fill: Color.WHITE

smooth: true

textOrigin: TextOrigin.TOP

clip: Rectangle { // calculations for layout

x: bind descText.x

y: bind (descText.y – 2)

width: bind (layout.width – 20)

height: bind ( layout.thumbGroupY – descTxt.y – 17)

}

}

stageContent = [

backRect, titleBar, nxtButton, bckButton, exitButton,

descTxt, thumbGroup, pageBttnGroup,

fullView, progressBar,fiv.saveBttn //names are self explanatory, last one is save button inside Scene Full Image view.

];

getImageData(); // Call Flickr REST API using standard Java Flickr API. Loads list of thumb image src, description, etc.

}[/code]

c. Transitions:

Now look at how Transitions are created. To achieve the animation effect, you have to play with the javafx.animation.Timeline, javafx.animation.KeyFrame. Again, these are generic words used in animation industry (same with Flash). If you are new to animation, let me define it for you. Timeline is the time scale of the animation which consists of number of frames through which animation will move. KeyFrame is the frame with concrete data i.e. Initial or final state of the animation and in-between the frames happens the transition that creates animated illusion. The animation used, when you select a thumbnail to view fullImage, is demonstrated below:

[code lang=”javascript”]

var tL:Timeline = Timeline {

rate: bind tLRate with inverse

keyFrames: [

KeyFrame {

time: 1s

values: [ opacity => 1.0 tween Interpolator.LINEAR ]

canSkip: true

}

]

};

…

function fadeEffect() {

if(visible) { // javafx.scene.Node.visible, if current stage is visible, its set true.

tL.time = 0s;

tLRate = 1.0;

opacity = 0.2;

visible = true;

} else {

tL.time = 2s;

tLRate = -2.0;

opacity = 1.0;

}

tL.play();

}

[/code]

Animations are so easy to code. I just loved it.

I don’t trust any hypes, statistics till I test them on my own. Proceed with the next section and you will know what convinced me here.

.

2. Benchmarking the JavaFX (Gallery example):

i. Hardware used:

Notebook: Dell XPS

Processor: Intel Core 2 Duo 2.2Ghz @800Mhz FSB

RAM: 2.5GB

Graphics: Standard Intel extreme

(I have a Nvidia notebook as well but I wanted to test it on the onboard graphics to check how bad can it get.)

Tools: Netbeans 6.5, VisualVM 1.1

ii. Invocation & Startup:

JavaFX startup is pretty heavy for initial 10 seconds. During this interval, It is supposed to load a large number of underlying classes.

The main loader is com.sun.javafx.runtime.main.Main.class, packaged inside the distributable Jar. In a web browser, actual invocation starts from the javascript from URL “http://dl.javafx.com/1.2/dtfx.js”.

This Javascript looks for “Javafx” method inside the HTML <script> tag. In this tag, information about the “JAR to load” is present. JAVAFX runtime Main.class takes over the control and loads the Projectname_browser.jnlp which invokes the actual jar user classes i.e. com.taranfx.* in this case.

Before loading your Main class i.e. com.taranfx.Main.fx, it loads all the base underlying classes to support the Javafx features.

a. Observations:

My application had import for around 200 classes and 20 classes were defined under com.taranfx.*. The Total classes loaded after the start-up was nearing 4000.

If you look at the graph above, loaded classes for first peek was 2500. This is the point where JavaFX started reading my com.taranfx.* package. This means, at all times for JavaFX to start empty, it will need 2500 runtime classes. During this time, (almost 6 seconds), CPU utilization is max. On my Dual core it was able to eat upto 70% CPU though it was using only 7mb of heap.

If you look at the CPU graph, the second peek was incurred when my classes started executing. This was the time when Request for Flickr REST API was being generated. During this, CPU utilization of 27%, Heap size of 12mb was observed. The third CPU peek came when response from Flickr was received, and images were starting to appear. Loading of 50 images (10in a row x 5 in a column) took peek utilization of 25.5%. As clear from Memory utilization graph, Images were being loaded and heap size was increasing in steps till 20mb of which roughly 13mb was being used. Immediately after this, a substantially GC call reduced the memory overhead. (after this watever memory increase you see is because of my further operations in GUI, we will consider them in next section)

.

b. JavaFX vs. Flash

Now, I had a similar application in Flash ofcourse pretty different in layout, etc but similar functionality. Let’s compare those statistics with JavaFX.

It was roughly 40% at first peak with RAM usage of 4mb, and then 20% second peek with 10mb, and 3rd peek 29% with 19mb RAM.

c . Conclusion:

All the performance statistics were pretty close to Adobe Flash but were mostly on the higher side which is but obvious because its VM 🙂

.

iii. Animated Transitions and Full Image load:

So after loading of thumbnails is over, next comes the main application. Navigating quickly between images as it prepares requests for each of the image to be downloaded for preview. Let’s discuss the Performance of the application during power user usage. Since the application has lots of animations specially Fade transitions, We will compare how well are those can run on our machines.

Please note, I have chosen animation mainly as fade as it needs alot of CPU juice to run smoothly. Infact, smooth fading was far from reality in Swing. So let’s see how well JavaFX handles this in new refined JVM.

Let’s now look at the profiling:

a. Key Observations:

Refer to the CPU, the first wave peek you see is at approx. 15 seconds from when all thumbs were loaded. This peek was incurred due to my first click, which triggered the very first transitioning of fading all 50 thumbnails screen to Full Image preview (class ). Fading was very smooth and what a surprise it took just 19% of my CPU. Are you kidding me JavaFX ? Fading involves a number of interpolated frames during the transition time (set to 2 seconds) and frame rate of decent 20 fps was observed (I used a screen capture tool that auto-detects frame rate of the screen, it gave 20.3 fps)

Moving on, I became a power user (clicking madly on all images and then returning back) at full pace. Clicked images were being loaded in background threads while new images being licked were having fading transitions, one by one being put to backround thread queue to load images from flickr. As expected, it resulted in good CPU utilization, though transitions still remained smooth as before. CPU wasn’t kicked much it ranged between 30 to 60% which is pretty expected, no surprises. But one thing impressed me, Heap Usage. It didn’t eat much of the Heap. At start, Heap size was 20MB (15mb used), it then raised only to 25mb after 40 seconds of power user activity. GC wasn’t kicked more than once and it reduced Used heap from 20 to 15mb making it less hungry for more Heap. I must admit, memory management was pretty good.

Now let’s look at the other part, the most active Threads.

Java.util.concurrent.FutureTask.run() ate most of the CPU. Because of high number of requests, large no of threads got created, and for obvious reasons, this had to be the highest usage. Second highest is javax.swing.SystemEventQueueUtitlities, which is a old class from the generation of swings exposing some generic UI utilities. This involves the fading, and other graphical operations. Third was sun.rmi.transport.tcp.TCPTransport, this was for TCP connection to Flickr. The CPU usage for this thread is during translation of TCP requests from Java to right to your OS protocol stack.

b. Conclusion

I’m still left astonished if this was possible inside VM! The Ability of Graphics (atleast for 2D) is brilliant. Later on when I took the same test to Nvidia platform, I did see noticeable differences. The Fade effect had risen from bare 20fps to 28fps.

3. The VERDICT!

The Pros:

– Solid API with bundled inbuilt features for almost anything you will need.

– Brilliant Graphics Rendering (2D)

– Low on CPU usage than previous generation of JavaVMs.

– Comparble performance for generic RIA.

– Excellent memory management. (it’s not just standard VM memory management, there’s more to it.)

– OpenSource: A More open approach to RIA in the industry as compared to Flash, Silverlight like AJAX.

– Universal Language for Desktop, mobiles, other portables.

The Cons:

Nothing in the world is without Cons, even JavaFX has it:

– Graphics and multimedia are powerful on JavaFX, but it runs in JVM and not the real system, hence graphics can never be as powerful as native applications like Adobe Flash. The high complexity advanced 2D, 3D graphics will suffer significant performance hits inside VM. Such aplications will have more floating point calculations and More frequent memory allocation/de-allocations which will choke VM. (Though, for low complexity 2D, jaavaFX might beat Flash)

– Another -ve is for Video and High definition: The mediaplayer (via API) in JavaFX is able to attain a decent framerate of 24/25fps and CPU utilization goes to peak during this playback over SD (Standard definition). Now if you are looking for HD content to go via JavaFX, it’s not possible at this time. I used the same hardware as in the benchamark. CPU utilization goes to peak to achieve that framerate for SD.

For Playing 720p and 1080p HD content, VM came to the knees, failed to provide any tolerable frame rates. Definitely, needs lot of improvement in this sector. May be Sun can develop native APIs to interact for each Nvidia CUDA, ATI graphics Kernel for each platform to accelerate this. This could encourage 3d gaming in JavaFX. (though this is very hard to do and maintain keepin platform independence in mind.).

– A big challenge awaits javafx to reduce Load times. To load startup classes, it takes 10-20 seconds depending upon the application and CPU you are using. Flash is much faster at this.

Definitely I found my effort worth while after days of playing with JavaFX. I can proudly say it will stand as a clear challenger to Flash (provided few things improve, specially load times). From the past trend of Sun, it has innovated in every field of Java and will continue to do so. And now that It’s with Oracle and Larry Ellison, I don’t have a doubt about its future.

Future could be JavaFX. Are you Ready?

Get Started www.Javafx.com

VN:F [1.9.22_1171]

please wait... Rating: 0.0/10 (0 votes cast)

VN:F [1.9.22_1171]