Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, July 25, 2015

Bangalore Java User Group (JUG)- July Meet-up

Today, we had very interesting sessions on Concurrent Garbage Collector and Completable Future by Deepak and Srinivasan.

Deepak, while taking about the Azul Garbage Collector covers:
- The basics of GC
- How we can proceed for a concurrent GC
- What are the challenges to achieve a concurrency in GC

Srinivasan while talking about the Completable Future covers:
- How the new Completable Future of JDK 8 is better than the old calls
- How the real life applications like Banking, Online booking systems can use this feature.
- What were the old bottleneck which got addressed.

If you are also interesting in joining Bangalore Java User Group, follow us on:

Our meetup page - http://www.meetup.com/BangaloreOpenJUG/
Our Facebook page - https://www.facebook.com/groups/1018617618156273/



 Soon, I will provide the links for the presentation.

Thursday, July 23, 2015

Java User Group Bangalore - Lets Rock !!

Guys, if you are a Java Developer and you are in Bangalore. It's the time to meet the biggest Java User Group in Bangalore. Do join us, in JUG-Bangalore.

Here are the talks of the month:

Azul JVM - Concurrent Garbage Collection 
Harish Babu 60 mins

Java 8 new Javascript engine call Nashorn 
Shekhar Gupta 45 mins 

Completable Future of JDK8
Srinivasan Raghavan 45 mins

Its a free to join place without any fee. We will provide you Snacks and Java :-). Keep rocking. Do join the Facebook group: https://www.facebook.com/events/730993017030025/

Tuesday, July 21, 2015

VM options for optimization (C1 and C2 compilers)

Many Java Developers often ask what are the flag options available for C1 and C2 Compilers or what are the flag options available for JIT compilers. Though most of the time our slides will cover some of the important VM options (-XX) but certainly we can't  provide the list of complete option in slides. This is actually quite a trivial job.
Here it goes:
1. Complete VM global flag option (redirecting it to out file):
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintFlagsFinal > out
wc -l < out
764  // Total available options, did on jdk7
2. If you will check without  UnlockDiagnosticVMOptions, the no.s will be bit less.
java  -XX:+PrintFlagsFinal > out
wc -l < out
672 
2. This document comes with the beautiful option of where it is been used like Product, C2 diagnostic, C1 Product and many more. So, just grep the out file with "C2" and see what options are available for you on C2 Compiler and which options are product options and which are diagnostic or logging options.
 cat out | grep "C2"  (Linux/Solaris/Mac machine option, find the equivalent to windows)
A list will come something like:
     intx AliasLevel                                = 3               {C2 product}
     bool AlignVector                               = true            {C2 product}
     intx AutoBoxCacheMax                           = 128             {C2 product}
     bool BlockLayoutByFrequency                    = true            {C2 product}
     intx BlockLayoutMinDiamondPercentage           = 20              {C2 product}
     bool BlockLayoutRotateLoops                    = true            {C2 product}
     bool BranchOnRegister                          = false           {C2 product}
     intx ConditionalMoveLimit                      = 3               {C2 pd product}
     bool DebugInlinedCalls                         = true            {C2 diagnostic}
ccstrlist DisableIntrinsic                          =                 {C2 diagnostic}
     bool DoEscapeAnalysis                          = true            {C2 product}
     intx DominatorSearchLimit                      = 1000            {C2 diagnostic}
     intx EliminateAllocationArraySizeLimit         = 64              {C2 product}
     bool EliminateAllocations                      = true            {C2 product}
     bool EliminateAutoBox                          = false           {C2 diagnostic}
     bool EliminateLocks                            = true            {C2 product}
     bool EliminateNestedLocks                      = true            {C2 product}
     bool IncrementalInline                         = true            {C2 product}
     bool InsertMemBarAfterArraycopy                = true            {C2 product}
     intx InteriorEntryAlignment                    = 16              {C2 pd product}
     intx LiveNodeCountInliningCutoff               = 20000           {C2 product}
 3. Running the same option for C1.
cat out | grep "C1" 
We can see:
     bool C1OptimizeVirtualCallProfiling            = true            {C1 product}
     bool C1ProfileBranches                         = true            {C1 product}
     bool C1ProfileCalls                            = true            {C1 product}
     bool C1ProfileCheckcasts                       = true            {C1 product}
     bool C1ProfileInlinedCalls                     = true            {C1 product}
     bool C1ProfileVirtualCalls                     = true            {C1 product}
     bool C1UpdateMethodData                        = true            {C1 product}
     intx CompilationRepeat                         = 0               {C1 product}
     bool LIRFillDelaySlots                         = false           {C1 pd product}
     intx SafepointPollOffset                       = 256             {C1 pd product}
     bool TimeLinearScan                            = false           {C1 product}
     intx ValueMapInitialSize                       = 11              {C1 product}
     intx ValueMapMaxLoopSize                       = 8               {C1 product}
 Enjoy Optimization, Enjoy JIT'ing.

Sunday, July 19, 2015

Just-In-Time Compiler Optimizations (Know your JVM)

JIT comes in these flavors:
 C1 (Client compiler) -client option
 C2 (Server compiler)-server option
 -XX:+TieredCompilation - Better decision of compilers.
Common Optimizations done by Just-In-Time (JIT) Compiler do:
 1. Eliminate dead codes and Expression optimization.
 int someCalculation(int x1, int x2, int x3) {
         int res1 = x1+x2;
         int res2 = x1-x2;
         int res3 = x1+x3;
         return (res1+res2)/2; 
 }
will be converted to
int someCalculation(int x1, int x2, int x3) {
 return x1; 
} 
 2. Inline Method
- Substitute body of the method (<35 bytes of JVM bytecode) - This provides the best optimization by JIT - A better inline that C++ 
For Example: 
int compute(int var) { int result; if(var > 5) { result = computeFurther(var); } else { result = 100; } return result; } 
If you call myVal = compute(3); it will get converted into myVal = 100;
3. Caching Technique:
Point findMid(Point p1, Point p2) { Point p; p.x = (p1.x + p2.x)/2; p.y = (p1.y + p2.y)/2; return p;
p1.x, p2.x -> It can convert into temp1, temp2 and can be cached.
4. Monomorphic dispatch:
public class Birds { private String color; public String getColor() { return color; } } myColor = birds.getColor(); 
If there is no other override of this method, it will convert into
public class Birds { String color; }
mycolor = birds.color; 
5. Null Checks Removal:
x = point.x; y = point.y; At JVM it is equivalents to: if(point==null) throw new NullPointerException(); else { x = point.x; y = point.y; }  
But if the code will not throw NullPointer for more than threshold reference, it will remove the if check.
6. Threading Optimizations:
- Eliminate locks if monitor is not reachable from other threads - Join adjacent synchronized blocks on the same object
7. Loop Optimizations: 
- Combining loops – Two loops can be combined if taking equivalent time. - Inversion loops – Change while into do-while. (why, just give a javap -c) - Tiling loops – Re-organize loop so that it will fix in cache. 
VM Args:
Xint – Interpreter mode Xcomp – Compiled mode Xmixed – Interpreter + Compiler -server → C2 compiler -client → C1 compiler -XX:+TieredCompilation → C1 + C2 (used by 32/64 bit mode) 
Logging Options:
-XX:+UnlockDiagnosticVMOptions -XX:+LogCompilation -XX:LogFile=<path to file> -XX:MaxInlineSize=<size> -XX:FreqInlineSize=<size> 

Saturday, February 08, 2014

Best Practices Java - StringBuffer

It's been 3 years when I have not done any blogging here. Some day before, one of my friends was asking me about StringBuffer and he has the point that I don't have any justification that why Sun has created StringBuffer.

I am writing this blog from a very rural village of Bihar, India. The common problem I found was people are not utilizing the time in best of work. Many of the kids go to the market to bring one-one item at a time. Alright, are we engineers also follow the same trend.

We use String as default and then we keep adding things in it. Something like:

String dontUse = "This";
dontUse +="is not right";

Alright, here is a small code I have written to understand the estimated time.

public class StringBufferExample {

public static void main(String[] args) {

String[] dontUse = new String[10000];
                //StringBuffer[] dontUse = new StringBuffer[10000];
for(int i=0;i<10000;i++) { }
long startTime = System.nanoTime();
for(int i=0;i<10000;i++) {
                        dontUse[i]= new String("this");
// dontUse[i]= new StringBuffer("this");
}
for(int i=0;i<10000;i++) {
                        dontUse[i]+="is wrong";
// dontUse[i].append("is wrong");
}
long endTime = System.nanoTime();
System.out.println(endTime - startTime);

}
}

Approx Time taken from this code: 5501435(ns) whereas if you run the commented code, it will take: 2258812(ns)
So, not visible but normal String operation for "simply" addition of two string is "twice" costlier than StringBuffer.

Running: javap -c -classpath . StringBufferExample (copying those lines which are costly), will clearly tell you why String operation is a costly affair(actually it was never a String operation, it changes things to StringBuffer and then again convert it by toString to String).


   64:  if_icmpge       97
   67:  new     #6; //class java/lang/StringBuilder
   70:  dup
   71:  invokespecial   #7; //Method java/lang/StringBuilder."<init>":()V
   74:  aload_1
   75:  iload   4
   77:  dup2_x1
   78:  aaload
   79:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/
String;)Ljava/lang/StringBuilder;
   82:  ldc     #9; //String is wrong
   84:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/
String;)Ljava/lang/StringBuilder;
   87:  invokevirtual   #10; //Method java/lang/StringBuilder.toString:()Ljava/l
ang/String;
   90:  aastore


Now in the next blog, I will cover how StringBuffer handles the capacity, how it enlarge its capacity and when. It's a pretty simple code written in JDK.


Monday, August 24, 2009

Java Debugging basics

Some simple debugging tools related to Java. These are for those who are new to Java.

1. Application is crashing : Most miserable one. Get your log file, try to analysis log. How to write log file, use Java Logger API. Java Logger had been introduced in JDK 1.4.2. The most awesome feature of Logger API is that you can use it in production without much overhead. The overhead is controlled by something called level in API. Level goes from FINEST to SEVERE. You can refer to O'Relly Book "Java, In a NutShell". I guess, it covers Logging API into a great detail.

Lot many things to know: Standalone application is crashing or web application. Its crashing with -client or -server option, appletviewer or browser, plugin or plugin2.

2. Application Hang: Most prominent reason for Hang is thread related. I don't know too many language but Java handles thread in most graceful way. What we can do when a Java Process or Application Hang:

- Hmm, get stack trace at Java and native level.
- Get to know current thread conditions and their status.
- Try to get core dump. Sometime, application will refuse to give you.
- Get to know machine detail. Almost all OS, use different thread model. Not only that in Solaris, 8 and 9 use different models. Sometime, it narrow down the problem, if you are luck :).

How to get all these information. Easy actually. Take help of Java Debugger, jdb(which is a part of JDK). In jdb, you can run the command like threads, thread, dump and many more. Take help of Windbg, if its a windows machine for native level. I find it useful and painful.

3. Your application is drinking memory: There is some memory leak. Best is to use jhat(part of JDK). First take a heap dump by using jmap, jconsole hprof. Pass that heap dump to jhat and it will bring a server and

dump all the information. Analyze where most of the memory is going. Writing to track the place from where memory is going. What is GC response on it. Change some arguments of GC and then give a try.


There are lot of JDK tools that help in analyzing JVM, threads, memory, process. See the list : http://java.sun.com/javase/6/docs/technotes/tools/

Garbage collector play important role in all of them, so always get to know what is best for what:- http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html (Even you know less about GC, you can't resist yourself finishing this page, this is so interesting). In terms of GC, everything is improving day be day and we have new GC, Garbage First aka G1 ready. With Vikram, I had one presentation on G1 in Sun tech days - http://developers.sun.com/events/techdays/presentations/locations-2009/hyderabad/td_hyd_garbagcollector_aroskar_choudhary.pdf.

If you have any wired debugging story related to Java, please share :). Also, visit Visual VM which is meant to integrate all the command line tools of JDK.

Monday, December 01, 2008

Java Plugin2 - Docs !


With Plug-in 2(Java 6u10), a whole new experience comes into Java Plug-in. I have mentioned the new features of Plugin2 in some of my presentations of 6u10.


For detail, please visit this link : http://java.sun.com/javase/6/webnotes/6u10/plugin2/index.html


Switching between old/new plugin:


Java Control Panel - Advanced - Java Plug-in - Enable the next gen plug-in.


(Check this link : http://www.java.com/en/download/help/new_plugin.xml)




By default, it will take new plugin, but untick it for old plugin.

Scene to Scene in JavaFX

Any middle or big application demands to change one window to other at some point of time. A window type of thing in JavaFX is represented by Scene and its each to switch between scene or to run multiple scenes.


Here is a small application in which clicking on image will put you in another window, written "Hello World"



package sample6;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;

var s_new:Scene;
var s = Scene {
content: [
Text {
font: Font {
size: 24
}
x: 10,
y: 30
content: "HelloWorld"
}
]
};

var s1 = Scene {
content: [
ImageView {
image: Image {
url: "{__DIR__}im2.PNG"
}
onMouseClicked: function( e: MouseEvent ):Void {
s_new = s;
}
}
]
};

s_new = s1;
Stage {
title: "Application title"
width: 250
height: 280
scene: bind s_new
}

So, its simple, on mouse click, I have bind a scene variable with a new scene. That's it !



Sparkling Glass

What to achieve: A sparkling glass(beer glasses are clean and shiny before beer get served) like this.



So, our aim is to make those sparkling effect on glass. Here is the code in JavaFX(things are little hard coded but better for understanding):


 
package sample;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.input.MouseEvent;
import javafx.scene.transform.Rotate;
import javafx.scene.shape.Polygon;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.animation.Interpolator;
import javafx.scene.shape.Circle;
import javafx.scene.Group;
/**
* @author Vaibhav
*/

var r = 0.0;
var t = Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames: [
KeyFrame {
time: 3s
canSkip: true
values: [
r => 360.0 tween Interpolator.EASEBOTH
]
}
]
}
t.play();
var op = 1.0;
var t1 = Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames: [
KeyFrame {
time: 3s
canSkip: true
values: [
op => 0.0 tween Interpolator.EASEBOTH
]
}
]
}
t1.play();

Stage {
title: "Sparkling on Glass"
width: 250
height: 480
scene: Scene {
fill: Color.BLACK
content: [
ImageView {
image: Image {
url: "{__DIR__}wineglass.png"
}
}
Polygon {
rotate: bind r;
translateX: 130
translateY: 100
scaleX: 0.5
scaleY: 0.5
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind op
},
Polygon {
rotate: 45;
scaleX: 0.25
scaleY: 0.25
translateX: 130
translateY: 100
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind 1 - op
},
Polygon {
rotate: bind r;
translateX: 50
translateY: 50
scaleX: 0.5
scaleY: 0.5
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind op
},
Polygon {
rotate: 45;
scaleX: 0.25
scaleY: 0.25
translateX: 50
translateY: 50
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind 1 - op
},
Polygon {
rotate: bind r;
translateX: 30

translateY: 120
scaleX: 0.5
scaleY: 0.5
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind op
},
Polygon {
rotate: 45;
scaleX: 0.25
scaleY: 0.25
translateX: 30
translateY: 120
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind 1 - op
},
]

}
}


Same animation in flash is here : http://www.entheosweb.com/Flash/sparkling_effect.asp

Java Market Trend

Today I got a mail from Carl. He works in a company which provides Marketing stats. Here are some of the exciting marketing stats of Java :


1. Median Salary :












Generated By: OdinJobs - Techonology Job Search Engine




2. Jobs Trend line













Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine



3. Salary Histogram :












Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine



Now, see the market increase in Java Gaming.And there is a reason behind it, people start realizing that Java is fast and a suitable language for gaming. It happened for quite a long time developed used to think that Java is a slow language and not meant for game.












Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine


Banking sector, this is quite obvious because of the market fall down, else it was little above than the last year performance.












Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine


Defense: This is quite an interesting market. It speaks about the robustness and security of Java. Defense finds it the best language for their purpose.












Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine


For more visit this link : Java Market Stats

Sunday, September 14, 2008

Filling eyes effect in JavaFX

This is one simulation of Golden Eyes :-D(with an ugly face). I tried to make one use of Gaussian Blur which is applied in the white color of eyes. Adding this spot in the eyes gives a real simulation.



package eyes;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Arc;
import javafx.scene.geometry.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.*;
import javafx.scene.effect.*;

var y: Number = 150;
Frame {
title: "Golden Eyes"
width: 500
height: 500
closeAction: function() { java.lang.System.exit( 0 );
}
visible: true

stage: Stage {
fill: Color.GRAY;
content: [

Circle {
centerX: 160, centerY: y
radius: 23
fill: LinearGradient {
startX: 0.0
startY: 0.0
endX: 1.0
endY: 0.0
proportional: true
stops: [
Stop { offset: 0.0 color: Color.GOLD },
Stop { offset: 1.0 color: Color.BLACK }
]
}
opacity: 0.9
},

Circle {
centerX: 160, centerY: y
radius: 10
fill: Color.BLACK
},
Circle {
centerX: 166, centerY: y - 5
radius: 5
fill: Color.WHITE;
effect : GaussianBlur {
radius: 6
}
},
Circle {
centerX: 250, centerY: y
radius: 23
fill: LinearGradient {
startX: 0.0
startY: 0.0
endX: 1.0
endY: 0.0
proportional: true
stops: [
Stop { offset: 0.0 color: Color.BLACK },
Stop { offset: 1.0 color: Color.GOLD }
]
}
opacity: 0.2
},


Circle {
centerX: 250, centerY: y
radius: 10
fill: Color.BLACK
},
Circle {
centerX: 244, centerY: y - 5
radius: 5
fill: Color.WHITE;
effect : GaussianBlur {
radius: 6
}
},
Circle {
centerX: 200, centerY: 180
radius: 100
fill: Color.SIENNA
opacity: 0.1

},
Polyline {
stroke:Color.BLACK
points: [
200,160,
220.0,220.0,
180.0,220.0
]
},
Path {
fill: LinearGradient {
startX: 0.0
startY: 0.0
endX: 1.0
endY: 0.0
proportional: true
stops: [
Stop { offset: 0.0 color: Color.BLACK },
Stop { offset: 1.0 color: Color.RED }
]
}
elements: [
MoveTo { x: 160 y: 240 },
ArcTo { x: 250 y: 240 radiusX: 100 radiusY: 100},

]
},

]
}
}

2+2=4 and so 2*2

Last week, our office celebrates OpenSource Mela. In code war, we got a programming contest in which the problem statement is :

5 * 4 / 2 - 5 + 2 = 7 (evaluated from left to right). So, input format is:

5 4 2 5 2 7

and output is to put into a valid expression format(all possible format). So, if its 2 2 4, then 2+2=4 and 2*2=4 is possible. I have written some code for this, which goes here :

package problemstatement1;

import java.util.List;

public class Main {

String input = "2 0 2";
String output = new String(); // 5 * 4 / 2 - 5 + 2 = 7
int resultVal = 0;
String operatorseq = new String();
int result = 0;
int totalcounter = 0;
boolean flag = true;

// converting input into easy format

String[] inputtoken = input.split(" ");
int[] numberseq = new int[inputtoken.length - 1];
int totaloperator = numberseq.length - 1;

public void isValid() {
if (inputtoken.length < 3) {
System.out.println("Usages ... Input Parameter should be three or more ");
System.exit(0);
}
}

public void processInput() {
try {
resultVal = Integer.parseInt(inputtoken[inputtoken.length - 1]);
} catch(NumberFormatException e) {
System.out.println("Parsing error" + " " + e);
System.exit(0);
}
for (int i = 0; i < numberseq.length; i++) {
try {
numberseq[i] = Integer.parseInt(inputtoken[i]);
} catch(NumberFormatException e) {
System.out.println("Parsing error" + " " + e);
System.exit(0);
}
}
}

public void showInput() {
for (int i = 0; i < numberseq.length; i++) {
// System.out.println(numberseq[i]);
}
}

public void getPermutation() {
GenerateOperators gen = new GenerateOperators("+-*/", totaloperator);
List v = gen.getVariations();
System.out.println("Possible Solutions");
for (int i = 0; i < v.size(); i++) {
operatorseq = v.get(i);
manupulate();
}
}

public void manupulate() {

result = 0;

for (int i = 0; i < operatorseq.length(); i++) {
if (i == 0) {
if ((operatorseq.charAt(i)) == '+') {
result = result + (numberseq[i] + numberseq[i + 1]);
}
if ((operatorseq.charAt(i)) == '-') {
result = result + (numberseq[i] - numberseq[i + 1]);
}
if ((operatorseq.charAt(i)) == '*') {
result = result + (numberseq[i] * numberseq[i + 1]);
}
if ((operatorseq.charAt(i)) == '/') {
try {
result = result + (numberseq[i] / numberseq[i + 1]);
} catch(Exception e) {
flag = false;
// don't do anything
}
}
} else {
if ((operatorseq.charAt(i)) == '+') {
result = result + numberseq[i + 1];
}
if ((operatorseq.charAt(i)) == '-') {
result = result - numberseq[i + 1];
}
if ((operatorseq.charAt(i)) == '*') {
result = result * numberseq[i + 1];
}
if ((operatorseq.charAt(i)) == '/') {
try {
result = result / numberseq[i + 1];
} catch(Exception e) {
flag = false;
// don't do anything
}
}
}
}
if (result == resultVal && flag == true) {
totalcounter++;
System.out.println("");
for (int i = 0; i < numberseq.length - 1; i++) {
System.out.print(numberseq[i] + "" + operatorseq.charAt(i));
}
System.out.print(numberseq[numberseq.length - 1]);
System.out.print("= " + result);
}
}

public void count() {
if(totalcounter == 0 ) {
System.out.println("NO EXPRESSION POSSIBLE");
System.exit(0);
}
else {
System.out.println("");
System.out.println("Total Possible Solution :" + totalcounter);
}
}
public static void main(String[] args) {
Main main = new Main();
main.isValid();
main.processInput();
main.showInput();
main.getPermutation();
main.count();
}
}


and one more file which is :

package problemstatement1;

import java.util.List;
import java.util.ArrayList;

public class GenerateOperators {

private String a;
private int n;

public GenerateOperators(String a, int n) {
this.a = a;
this.n = n;
}

public List getVariations() {
int l = a.length();
int permutations = (int) Math.pow(l, n);
char[][] storeCombination = new char[permutations][n];
for (int x = 0; x < n; x++) {
int temp = (int) Math.pow(l, x);
for (int p1 = 0; p1 < permutations;) {
for (int al = 0; al < l; al++) {
for (int p2 = 0; p2 < temp; p2++) {
storeCombination[p1][x] = a.charAt(al);
p1++;
}
}
}
}

List result = new ArrayList();
for (char[] permutation : storeCombination) {
result.add(new String(permutation));
}
return result;

}

public static void main(String[] args) {
GenerateOperators gen = new GenerateOperators("AAAMMBR", 7);
List v = gen.getVariations();
for (int i=0;i String s1 = v.get(i);
System.out.println(s1);
}

}
}

Feel free to use this code :-).


Wednesday, August 06, 2008

JavaFX Reflection Game !

On the way to exploring little more API of JavaFX, I reached to a fair animation. That is reflection. Here is the output of "crying baby".
Here is the code:

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Circle;
import javafx.scene.paint.Color;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.effect.*;

Frame {
title: "Crying Baby"
width: 400
height: 700
closeAction: function() { java.lang.System.exit( 0 );
}
visible: true

stage: Stage {
fill: Color.WHITE
content: [
ImageView {
x: 100
y:10
image: Image {
url: "http://www.powermixradio.com/GGG-SAD-CARTOON.jpg"
}
effect: Reflection {
bottomOpacity:0.1
fraction: 1
topOffset: 50
}
},
ImageView {
x:0
y:300
image: Image {
url: "http://www.toyotapartsstore.com/images/71111_2_%20mirror_8CE1.jpg"
}
opacity:0.5
}
]
}
}


Things to watch:

1. Effect: Reflection -

bottomOpacity:0.1 - set the opacity of image in reflection.

fraction: 1 - set how much part of the image should come in reflection.

topOffset: 50 - How far image from the focus. There are some more useful parameters in this.

2. Opacity of second Imageview allow me to see the reflection of first image, else it will cover the reflection.

On the way to make some moving animation, but I don't know what happened to the support of gif image. gif image works like static image, don't know why ?

Monday, August 04, 2008

Play with Flickr API in Java !

I decided to play with Flickr API's for Java FX coding. But in between I found myself in hell and I started with Java :-). As all of you know Flickr Support hell lot of API to view Image, to search image, to search comment, Image translation, Image upload and many more. Check out here for detailed API. Now using these API's are not at all tough, because its all a game of XML.

Here I have written a small code, which do this :

1. It search one image(it can work for more than one image) from search API of Flickr.
2. It writes the search data on a XML, which I am copying at D:\Hello1.xml.
3. And finally the code is using XML parsing techniques to get the information required for image view.
4. Then I use JDK6 feature of Desktop and open the default browser with the parsed URL. And
Congratulations, you can see the image.

Code, can look little big because of bad coding and writing lot of repetitive things :D.

package flickrapp;

import java.awt.Desktop;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.*;
import java.net.*;
import java.util.*;

public class Main {

public static void main(String args[]) throws Exception {
URLConnection uc = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e3471e67d4ac10c64055420d9b211b4f&per_page=1&text=Bangalore").openConnection();
DataInputStream dis = new DataInputStream(uc.getInputStream());
FileWriter fw = new FileWriter(new File("D:\\Hello1.xml"));
String nextline;
String[] servers = new String[10];
String[] ids = new String[10];
String[] secrets = new String[10];
while ((nextline = dis.readLine()) != null) {
fw.append(nextline);
}
dis.close();
fw.close();
String filename = "D:\\Hello1.xml";
XMLInputFactory factory = XMLInputFactory.newInstance();
System.out.println("FACTORY: " + factory);

XMLEventReader r = factory.createXMLEventReader(filename, new FileInputStream(filename));
int i = -1;
while (r.hasNext()) {

XMLEvent event = r.nextEvent();
if (event.isStartElement()) {
StartElement element = (StartElement) event;
String elementName = element.getName().toString();
if (elementName.equals("photo")) {
i++;
Iterator iterator = element.getAttributes();

while (iterator.hasNext()) {

Attribute attribute = (Attribute) iterator.next();
QName name = attribute.getName();
String value = attribute.getValue();
System.out.println("Attribute name/value: " + name + "/" + value);
if ((name.toString()).equals("server")) {
servers[i] = value;
System.out.println("Server Value" + servers[0]);
}
if ((name.toString()).equals("id")) {
ids[i] = value;
}
if ((name.toString()).equals("secret")) {
secrets[i] = value;
}
}
}
}
}
System.out.println(i);
String flickrurl = "http://static.flickr.com/" + servers[i] + "/" + ids[i] + "_" + secrets[i] + ".jpg";
try {
URI uri = new URI(flickrurl);
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}

if (desktop != null) {
desktop.browse(uri);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (URISyntaxException use) {
use.printStackTrace();
}
}
}

Now see this line :

URLConnection uc = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e3471e67d4ac10c64055420d9b211b4f&per_page=1&text=Bangalore").openConnection();

Here some important thing to see :

http://api.flickr.com/services/rest/?method=flickr.photos.search -> this is the way to write Flickr API.

api_key=e3471e67d4ac10c64055420d9b211b4f -> required for service. This is my api_key, you can have your own. Just go to flickr service and generate your API_key

per_page=1 -> Here is what I meant one image, if you can change this to 10. It will gather information of top 10 images in XML file.

text=Bangalore -> Sorry, I have hard coded it for now. This is the search string.

Now, look at the XML file get generated in D:\Hello1.xml. You can see one entry with tag photo inside photos. So, we need to take some data from this XML file and add in proper style to get the correct URL and that is here:

String flickrurl = "http://static.flickr.com/" + servers[i] + "/" + ids[i] + "_" + secrets[i] + ".jpg";

Again, lot of things are hard coded(which I will correct in next post). Since only one image (i=0). I am assuming its a jpg image :D. Now calling Desktop API, you can load this image on default browser.

Now, this is still a live question, for certain keyword search, it gives the same result like when I search for keyword "Vaibhav", code and search box of Flickr provided the same result(which is not my photo :-( ) whereas if I search on things like "Bangalore", result is not similar for many cases. I don't know how Flickr handles it internally.

Probably next I will try to upload image or translate image but in Java FX :-)

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.

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.