Saturday, March 31, 2007

Class file demand for which Java version

Someday back I got a call from my roommate's friend asking about that he has moved some class files from one system to other and now those class files are not running. I guess he got those class files from somewhere and he has no idea about which version of JDK it will run.

It's not such a tough job to find out that which version of JDK your class file is demanding. What we need to know is the format of class file and rest is like in your hands. Just look at the code for getting more clear picture.

import java.io.*;
class CheckClassFileFormat {
public static void main(String[] args) throws Exception
{
int magicNumber;
int minorVersion;
int majorVersion;
// and many more
DataInputStream data = new DataInputStream(new FileInputStream(args[0]));
magicNumber = data.readInt();
if(magicNumber !=0xcafebabe) // why 0xcafebabe.. read it, its so funny
{
System.out.println("Not a correct class format");
System.exit(1);
}
minorVersion = data.readShort();
majorVersion = data.readShort();
String version ="no version";

/*The Java virtual machine implementation of Sun's JDK release 1.0.2 supports class file format versions 45.0 through 45.3 inclusive. Sun's JDK releases 1.1.X can support class file formats of versions in the range 45.0 through 45.65535 inclusive. Implementations of version 1.2 of the Java 2 platform can support class file formats of versions in the range 45.0 through 46.0 inclusive.*/

if (majorVersion < 48) {
version = "jdk1.3.1";
} else if (majorVersion == 48) {
version = "jdk1.4.2";
} else if (majorVersion == 49) {
version = "jdk1.5";
} else {
version = "jdk 6";
}
// can follow up the same line for new releases.

System.out.println(args[0] + ": correct jdk version is " + version);
}
}
Just pass the classfile (like Test.class) in argument and we get to know on which JDK it need to run :)

Sunday, March 25, 2007

String vs StringBuffer vs StringBuilder

Let me first tell you what is StringBuilder. StringBuilder is a class analogous to StringBuffer added in JDK 1.5. This class is designed to use in place where StringBuffer is used by single thread(like in most of the cases). According to documentation, StringBuilder should work faster than StringBuffer. So " thread unsafe, fast".

I was reading one of the posts of orkut Java community asking "what is this capacity in StringBuffer and even we can add two strings from String class why to go for StringBuffer". Valid question ! GC need to work little more in case of String, but thats fair. As a java wellwisher let me try to do some publicity of Java API :D. And here it goes:

No don't use String class for concatenation operation, always use StringBuffer/StringBuilder and let me tell you why ?

This is a simple Java code for string addition in String and StringBuffer:

class StringTest {
public static void main(String[] args)
{
String s = "just a string";
s = s + "add me too";
System.out.println(s);
/*
StringBuffer s = new StringBuffer("just a string") ; //StringBuilder s = new StringBuilder("just a string");
s = s.append("add me too");
System.out.println(s);
*/
}
}

Alright, now have a look on the bytecode of this program(don't be panic).

>> javac StringTest.java
>> javap -c StringTest

Compiled from "StringTest.java"
class StringTest extends java.lang.Object{
StringTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object.
":()V
4: return

public static void main(java.lang.String[]);
Code:
0: ldc #2; //String just a string
2: astore_1
3: new #3; //class java/lang/StringBuilder
6: dup
7: invokespecial #4; //Method java/lang/StringBuilder.
":()V
10: aload_1
11: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/
String;)Ljava/lang/StringBuilder;
14: ldc #6; //String add me too
16: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)
Ljava/lang/StringBuilder;
19: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
22: astore_1
23: getstatic #8; //Field java/lang/System.out:Ljava/io/PrintStream;
26: aload_1
27: invokevirtual #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
30: return

}


Just see line no. 11. Interesting, the plus sign we used for addition is not as innocent as it looks. String itself use StringBuffer(StringBuilder) to add two strings and hence taking much more time than normal append operation done by StringBuffer. Let me give you more evidence, run verbose option and check the time

>> javac -verbose StringTest.java

and check the other one, that is, with StringBuffer one.

You can clearly figure out the time difference and make a try with StringBuilder, time should reduce furthermore.

So, how is my publicity :D

Tuesday, March 20, 2007

Bug Patterns in Java

An attitude of solving the problem when it aroses is always be so called " a lovely" behaviour of Software Engineers and so I. Most of us love this and never bother to read book :) . Anyway with a half-hearted mind, I start reading a book "Bug Patterns in Java". In the first glance name of the book suprised me becasue I never before saw a language book which discuss only about bugs. I liked the title and started the book. Also, as java becomes a mature product, a maturity of something around 11-12 years, resolving any bug of this language is a nightmare's job.

Author,Eric Allen started with a very macro level saying every bug falls under a pattern and if not then go ahead and make a pattern for it :). Let me tell you about one of the most common patterns. One pattern call "Rogue tile", the cause of this bug is we do copy paste of code, bug get fixed in the orignal copy and we forget to fix it into the copy paste code. So funny, but yes this is one of the most common errors we used to do.

So far, so good. Hoping for something great out of it :)

Wednesday, March 07, 2007

JDK 1.7 - Whats New ?

I remember the exact date when Mustang got released. Mustang is going great because of it's deadly features like JS support, Annotations and many more.

Moving forward to JDK 1.7-Dolphin which has a expected release in 2008! Whats new ?

I am making a complete presentation on Dolphin and will upload it soon ! Proposals are:

1. SuperJAR's - this is something really cool

2. Co-bundling with other language interpreter like JRuby, Jython.

3. Closures in java - something in one line we can understand local variables for a function - kept alive after the function has returned

4. More enhancement with Java Persistence API

and many more ...

The new JDK comes into a new flavor of open source, so get ready >

Tuesday, February 27, 2007

Pattern Class

Finite Automata ! Remember ! We used to make a lot of Automata at college time. Making Pattern is one of the most tricky jobs and we need to take care of lot of things.Best Part of the whole story is JDK 1.4.2 onwards support Pattern Class and believe me its simply awesome.
So, I decided to make a check for Class name, if a class name starts with Caps its a perfect one else not as per Java coding guideline. So, here is my simple class which I need to check :

class box {
int width = 0;
int height = 0;
}

Now look at the checks (all these are valid )

class Box
class (space) Box
(space) class
Box
public class Box

So, Decided to make a pattern ".*class[ \t\n\f\r]+[A-Z].*" means anything before the String class is fine, there can be space,tab in between class and classname(more than one,so +) , classname should start with a Caps. I am not checking any other character except the first one, with the assumption that file is already a compiled class.

There can be a lot more optimized pattern and more you optimize,more you feel happy :). Here goes my simple,ugly written code that checks the coding standard(only for class name, and that even for one class only :D) box.java file.

See hoe easy to make a option say java -checkstandard which checks for the correct coding guideline in .java file. And if its not according to coding guideline, we can throw the error and why to throw the error, we can replace it with right name(right according to Java Standard). So the code will change

class box {
int width = 0;
int height = 0;
}

into

class Box {
int width = 0;
int height = 0;
}


// Here goes the code //

import java.io.*;
import java.util.regex.*;

class ClassNameChecker {
public static void main(String[] args)
{
String line;
String sub;
try {
BufferedReader in = new BufferedReader(new FileReader(" box.java"));
line = in.readLine();
Pattern p = Pattern.compile(".*class[ \t\n\f\r]+[A-Z].*");
Matcher m = p.matcher(line);
if(m.matches())
{
System.out.println("Class Name follow Java Coding Guidelines");
}
else
{
System.out.println("Not a Java coding Standard");
}
}
catch(Exception e)
{
//something something
}
}
}

Tuesday, February 13, 2007

Next Decade is challenging ...

Revolution in Science is most unlikely in last 2-3 decade. I guess adoption of Internet was one and the only revolution of last few decades. But if we consider optimization, we did a great job ! From maintaining diary to writing blogs, from railway counter reservation to e-reservation. Very well depicted by this youtube video of Web 2.0



But I have a gut feeling that in the upcoming decade we are going to see some of the revolutions. And here I get the first news: "First Quantum Computer Tuesday". British Columbia-based D-Wave will demonstrate the world's first quantum computer this Tuesday. D-Wave is doing a good job in making Quantum Computers commercial but in spite of hard work they are fighting with Financial optimization.

Saturday, February 10, 2007

File Transfer ...

I was looking at all the possibilites of transferring file from one system(source system(s)) to other(target system) through pure java code. Socket programming is one of the ways suggested by my friend. But it seems to be a tedious job... opening connection, sending request, closing connection. And the base line truth is that I don't know how to do these all :).

I was searching in Java Library for file transfer and I saw Java FTP client Library support. We can upload or download files from remote computer running an FTP server simply with some method calls.

Look at this code:

FTPClient objectClient = new FTPClient();
objectClient.connect("SystemName","username","password");
objectClient.download("D:\\Myfile\\","RequiredFile.txt");
objectClient.disconnect();

FTPClient Package was supported by Sun, its never be a part of jdk package and I guess it was deprecated now :((
Any simple idea to do file transfer ?

Friday, February 02, 2007

Dead or Alive !!

Ahh this time its cool. Again a good conversion but this time I guess Java is going pretty cool. Work is to write a script (no script, program :D ) which checks the status(Dead or Alive) of Network machines. Yes an easy job for scripting language. Believe me, much easy in java as well. And here it goes:

import java.io.*;
import java.net.InetAddress;
public class MainClass {
public static void main(String[] args) throws IOException {
try {
int timeout = 2000;
BufferedReader br = new BufferedReader(new FileReader("machine.txt"));
String machineName = null;
while ((machineName = br.readLine()) != null) {
InetAddress address = InetAddress.getByName(machineName.trim());
if (address.isReachable(timeout))
System.out.println(address + " is Alive");
else
System.out.println(address + " is Dead");
}
} catch (Exception e) {
System.out.printf("Unknown host");
}
}
}

Thanks to my team member to add this reading file code. If you remove file reading lines, code is not more than 4-5 lines. machine.txt contains name of the machines like
Machine1
Machine2
Machine3
Dabba4

I have compiled this code on JDK 1.5 but it should run on the lower version of JDK's as well (hopefully).

Tuesday, January 30, 2007

Running Javac from Java !

Oh Long time, No post .. So I decided to go for one :). I suspended the thread of JVM Part-N because some of my friends told that these things are also written in book, write something extra. For writing extra, I don't have knowledge :D

Anyway, as we all know Scripting language is the most powerful language for running real application and most of the time I get it challenging to convert that script code into Java code, but believe me I am always ready to take this challenge. So this time my challenge was to run set of Java codes from a single Java Program. In general we run java code by opening cmd and doing those javac,java.

Again, its a damn easy job for a scripting language, but ... Ah come on you are a java programmer. And here the result, though currently I am running one Java code only from other Java Program (sorry for writing the code in a bad way)

import java.io.*;

class JavaCode {
public static void main(String[] args1)
{
com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
File file = new File("V.java");
String filename = file.getName();
String classname = filename.substring(0, filename.length()-5);
String[] args = new String[] { filename };
int status = javac.compile(args);
System.out.println(status);
}
}

(Some bad naming convention, some crap hard coding.. but you can pardon me for that :D ). Some unused part of code like taking classname, I am going to use it further to run the code. Ok this code is compiling and telling the status of V.java ...some Helloworld code (please put both in same location :) )

Ok so next is to run and print Hello World ... Not a tough job :)

Sunday, January 07, 2007

JVM Internals – Part II (Space Organization)

(Click on the main title to go for Part I)

In my previous post, I forgot to write about JVM specification (mind it, it’s a specification, Sun implementation of this is HotSpot, there are many others). JVM specification is written by Tim and Frank (The JavaTM Virtual Machine Specification, this is a free download book written by them). This specification is basically written in three parts ...saying:

~ A set of instructions – Bytecode
~ A binary format – Class file format
~ An algorithm for identifying programs that can’t compromise the integrity of the JVM – verification.


Yes, so coming to the point. JVM is divided into 4 conceptual data spaces:

# Class Area – where the code and constants are kept
# Heap – home for object
# Java Stack – keep tracks on method invocation and data associated with that
# Native Method Stacks – Something to do with native method

Lets take an example … where is our lovely class Foo :)

Class Foo {

public static void main(String[] args)
{
System.out.println(“Hello World(s)”);
}
}

So tell me how many object we have?

We have 3 objects: args, out and Hello World(s). All goes into Heap.

Class Area:

Class: Foo
Method: main ( actually we have main method descriptor here)

Java Stack:

It has stack handling the push and pop of local variables like Hello World(s), out and args.

Native Method Stack: I am relaxing :)

Stack going up and down is a bogus story.

So, I am directly moving on Garbage Collector >>>

Saturday, January 06, 2007

JVM Internals - Part I

Beginning of New Year seems to be challenging for me. I am not getting enough time to recollect my ideas and write a blog on that. But in the end of last year, I decided to write blogs on JVM internals from very basic, so that a person who knows Hello World in Java can understand it. And here it goes:

Everything is sequential in this story and the most difficult is to find the entry point. Most of us are taking VM as a black box but looking inside this black box in not a tough job (neither an easy job).

VM is a machine dependent code that sacrifices itself to make java application machine independent. Lets first see the Hotspot into programmers perspective than latter we will analyze it on designer/architect perspective. Around 160 MB of this code written in C++ has 3 major parts:
~ Runtime Compilers
~ Garbage collectors
~ Everything else (JNI code, assembler code, oop (ordinary object pointer) code)

I will talk about all these later in my blog. So the folder structure goes something like this:
- vm
---- gc
---- runtime
---- compiler (communicates with other code of VM)
---- code (for Justin Time Compiler)
---- optimization
---- JNI (Java Native Interface to interact Java with c, c++ and vice-versa)
---- asm (assembler generated by VM)
---- oop (ordinary object pointers are java objects written in C++)
---- ...
---- ...

Understanding VM means understanding these parts. I will try to cover all of them in my upcoming blogs. In Sun, teams are dedicated for all these and believe me runtime people even don’t talk with gc people.

Sunday, December 17, 2006

Open Source - 2500 years old war

Something around 2500 yrs back ancient Egyptians used to keep their mathematical knowledge secret, known only as priests. But then Greek got some of this knowledge and try to develop it openly through publication on papyrus - the ancient world's equivalent of the Internet.

I was looking at some of the open source licensing ways(and story as well) , yep, they are cool.

GPL is the most common amongst all and it says OPEN EVERYTHING. OPEN in open source means "OPEN AND FREE".

In GPL : Software - is free, copied must be free,must provide source, modified and derived work must be open(this is somewhat panic for local application dev.er's).

Other common licencing is LGPL(Lower GPL), which according to GNU should be used under specific circumstances. There may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard.To achieve this, non-free programs must be allowed to use the library(which is against the honour of GPL) and hence LGPL.

Whereas in BSD, Redistributions of source code must retain the copyright notice.The best part of BSD is application that develops on the top of BSD software can be sold. Most of our Kernels comes under this category, like Unix kernel or Darwin(Mac Kernel).

Market is flooded with Software Licences. All the gaint software when goes in the market as open source, the company made a new Licencing way for them. First time it not happened with Java! Open JDK belongs to many of the licenses. It basically uses GPL, LGPL and ClassPath Exception(one more intersting license).

Despite of the fact that there are so many licenses in the market, open source codes are not safe and they are used in many illegal ways. Becasue these licenses dont have the capabilty to put a check on the submodule part or the logic part.

Friday, December 08, 2006

Welcome Mustang !!

So today is the party time for Mustang. Looking at some of the cool features of Mustang :

~ API for System Tray: Our new AWT package contains two new classes SystemTray and TrayIcon. More or less provide everything that you can do with system tray.


~ Password Acceptation from Console: A new class - java.io.Console has been introduced to define console IO operation. One of the good features - you can take password from console.


~ Mix JavaScript with Java: This is one of the demanding features that developer want to of AJAX in market.

~ Support of Web Service: Awesome support for writing XML webservice client application.

In the rest, there are many more:

Tuesday, November 28, 2006

MyGame

Today I was thinking of all the games I used to play in my school time. And side by side I was also looking at the advancement of Game Programming. More or less all the Game which I used to play on paper and pencil are now automated and I can play on Computer with screen, mouse and keyboard.

I can remember one of the my favourite game that not seems to automated (I guess). The game is something like this:

We call it "Army Man" Game or "Tank" Game. On top and bottom of a paper, we have 3-3 army men like



1-------------------------------------------2---------------------------------3
.-------------------------------------------.---------------------------------.












.--------------------------------------------.---------------------------------.
1--------------------------------------------2---------------------------------3


You can force any armyman at anytime to move, but it should be one at a time. He will fire a bullet, that we used to do by sliding the pencil. And then you need to put a dot on the end of his path,that is, the path covered by pencil. Now its the time of other side army man to fire the bullet. Sameway you can dot his path. Both need to do this till one of them intersect the path of other. This game is looking very simple, but actualy its not. You need to put your head, when to go defensive and when to go aggresive. Also when both the teams are going straightway, you can go aggesive but if you missed, other will kill you.

Game finished, Rub the paper and start again. Best time to play this game was our Geography class :D

CAN WE AUTOMATE THIS GAME !

Monday, November 27, 2006

Java Code and Version Dependency

If you are a person who plays with different versions of Java, according to your business need, client need or your interest. Be careful for java version dependency. Ok, let me show you an example, this is the code I was trying in morning:

class StringTest {

public static void main(String[] args)
throws Exception
{
String s[] = new String[10];
String news = s[-1].valueOf('a');
}
}

Nothing great in this code, but will this code give an exception or not ? s[-1] is ofcourse a negative index array value but mind it method "valueOf" is a static method and hence not depending on the instance of the class. The result is quite interesting:

jdk 1.1 - running perfect.
jdk 1.2 - throwing an error.
jdk 1.3 - running perfect.
jdk 1.4 - throwing an error.
jdk 1.5 - throwing an error.

Thanks to my office system , which has all the java versions. Hmm, result is quite interesting.

I start searching the problem in "Google" and I got an awesome article, again on Javaworld.com which practically not solved my problem but at least relaxed me (Click on the main title to go on Javaworld.com page). Lots of things to read off, I can't write whole in blog :)

Thursday, November 23, 2006

java -ddoc option

One customization :


There is now more than lakh's of project developed in Java, that went for a maintenance, enhancement and servicing. The common problem in which most of the company stuck of is with the chain of ongoing and incoming employee. For a new engineer its difficult to understand the code written by someone else. And the worst happens when they don't have any supporting document to understand the code.

I am here proposing a java -ddoc option which generated a HTML(XML) format design document of the work flow of the code along with the output of the code.


It tells user about the class variables, share variables, method flow and Native API's(if any). Being Java an Open Java, engineers can understand the internal functionality and can perfectly understand the requirement of the written code.

Wednesday, November 22, 2006

Java is Slow ?

Are you feel anything bad about Java ?
Ya, its damn slow.

This is a inherited sentence from someone, not a self-checked statement. Our teachers used to say so, and so our seniors and so we.

Today, I was compiling some of the native API's where the function body is actually a CPP or C code. Just came across a paper " .P.Lewis and Ulrich Neumann Computer Graphics and Immersive Technology Lab University of Southern California " regarding the performance of Java against C++. There are many things to surprise of.

Let me discuss few of them:

1. Java performace is comparible to CPP and in some cases better than CPP. Not only this its improving ... !
Operation Units C Smalltalk Java
Polynomial 10th degree msec. 1.1 27.7 9.0
Neville Interpolation msec. 0.9 11.0 0.8
LUP matrix inversion sec. 3.9 22.9 1.0


2. Java performance at the time to be somewhere in the middle of C compiler performance - faster than the worst C compilers, slower than the best.more recent java(1.4) and gcc(3.2), using full optimization.This time java is faster than C the majority of the tests, by a factor of more than 2 in some cases...


And in theories YES, many reasons:

http://www.idiom.com/~zilla/Computer/javaCbenchmark.html

It's most Adaptable, not the most Powerful, who survives ! :)

Thursday, November 09, 2006

Garbage Collector ... Wow !!

Garbage collector is one of the most toughest code that is written under JVM. Highly optimized but not yet fully optimized code !

Most of the time we think as an application developer on Java, that GC is something which is not under our control and handled by JVM only and this is one of the place where we are really killing our application. Java HotSpot (JVM) gives 'n' number options to optimize GC according to the application need and to be frank this 'n' is 63. Some of the optimization is now deprecated in Mustang(jdk1.6) .

We can have several questions like how we can optimize our code!

Let me tell one perfect analogy that I saw someday back on JavaWorld for GC. Here it goes :

You are owner of a city, small city say 'JavaVelle' :) and in your city all the ppl are software eng'er. They are using too much of Computer and Car . Being small city there is only one main road in your city. Now, Dumping of computers and Cars is becoming too much and now you as an owner of the city want some garbage ppl to come and collector the garbage.

So, he is all the time coming with a big truck and collecting all the garbage and then putting it out of the city. But his truck is so big that when his truck is on road other ppl cant move here and there, and hence creating a congestion and not only that the biggest problem is Police and Ambulance type of critical process cant stop because of Garbage Truck.

This is the true scenario with GC. When JVM is running the GC to collect the Kachara (Garbage) it stop all the current running process. But some process which are real time or some which has too many client to serve cant stop like that. Sun provides a smart solution in Jdk 1.4 and smartest in Tiger release(JDK 1.5). It really based on some hopeless assumptions, like New object will die early, but it holds good. We are not going to discuss the whole process but as an application developer on Java, We can optimize the GC according to our own need. How ???


If you have a single-processor client machine and are having problems with pause times in your application, try the incremental garbage collector. This might help with perceived performance, even though it may decrease real application performance somewhat. Remember that perceived performance is usually more important than real performance for client applications. If the incremental garbage collector doesn't help (or doesn't help enough), and you have plenty of RAM, try the concurrent garbage collector.

If you have a single-processor server machine with lots of memory and experience trouble with application pause times, try the concurrent garbage collector.

If you have a multiprocessor machine, especially with four or more processors, try one of the parallel garbage collection algorithms. These should significantly decrease pause times. If you have lots of memory (gigabytes), use the scavenging collector; otherwise, use the copying collector.

Command-line switch

-XX:+UseParNewGC Parallel copying
-XX:+UseParallelGC Parallel scavenging
-Xincgc Incremental [none] Mark-compact [default]
-XX:+UseConMarkSweepGC

If you just want to check a demo, make a program with Lot of GC work. And then try these commands.

Example :
Test.java
javac Test.java
java -XX:+UseParNewGC Test

javac Test.java
java -XX:+UseParallelGC Test

javac Test.java
java -Xincgc Test

For web application developer, we need to make change in Web Container. I havn't try this but will do soon :)

Really want to go in detail, please check the Title Link.

Wednesday, October 11, 2006

Yes... I can believe on this

2.5 yrs back, when I was in 3rd year of my B Tech, I saw a dream... A dream to work with Sun That time I liked this company becasue anywhere if its come Open Source you will heard of Sun. Even today the reason is same.

Knowledge belongs to the world, we cant sell and buy it.

Wednesday, September 20, 2006

Sun going to add Non-Java Support to JCP

Interoperability is the first 'HARD' term I heard when I started my Java Course some 2 years back. It simple means how Java is showing it's behavior when it come across some non-Java component. We can say something like cross language, cross platform.

Dealing with other language is really a tough job, especially for Java because if its platform independency. In all of the problem we have a good news, Sun has proposed a new JSR(Java Specification Request) to make changes to the JCP. This JSP, JSR 306 also proposes more fundamental changes to the process, including allowing non-Java implementations of a JSR's specification; the ability to create liaison relationships with other standards organizations; easing the migration of pre-existing technology toward an agreed-upon standard; and the availability of a TCK (Technology Compatibility Kit) and associated licensing information upon completion of a JSR.
"This makes sense if you look at the emergence of concepts like Web services and service-oriented architecture," Kluyt(Chair of JCP) said. "Enterprises face very mixed environments where they have to make different architectures work together."