Saturday, February 09, 2008

Sorting with Different Locale

Sorting is always a tricky game in any language. Language like Java has its own high class sorting API's. But have you ever think, how sorting works in different locales ? How it work in French or in Spanish? Lets have a look...

This is my String Array which I want to sort:
String[] names = {"fácil", "facil", "fast","Où", "êtes-vous", "spécifique", "specific", "ou"};
It contains words of French Locale(some of my fav. words like Où :-) )
And here goes our typical sorting program:

String[] names = {"fácil", "facil", "fast","Où", "êtes-vous", "spécifique", "specific", "ou"};
List list = Arrays.asList(names);
Collections.sort(list);
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.print(itr.next()+ " ");
}

And the result:
Où facil fast fácil ou specific spécifique êtes-vous

Result can surprise you and can make your French friend angry :-) because he never want "fast" should come before "fácil", just because there is one special 'á' (sorting is true according to UNICODE sequence but not according to locale)

To face this problem JDK comes with something called Collator (I guess in 1.4 onwards) which take care of locale while sorting.
Collator is an abstract class. You can look the source code at location in Openjdk: jdk\src\share\classes\java\text\Collator.java. Highly documented file.

Collator has some flavors like PRIMARY, SECONDARY, TERTIARY, IDENTICAL which all tells what need to take care while sorting. Please read the javadoc for detail.

Now here is my simple code:

import java.text.*;
import java.util.*;


class CollatorTest {

public static void main(String[] args) {
String[] names = {"fácil", "facil", "fast","Où", "êtes-vous", "spécifique", "specific", "ou"};
List list = Arrays.asList(names);
Collections.sort(list);
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.print(itr.next()+ " ");
}

Locale[] loc = Collator.getAvailableLocales();

/* for(int i=0;
&<
{
System.out.println(loc[i].getDisplayName());
}
*/
Collator myCollator = Collator.getInstance(new Locale("fr"));
myCollator.setStrength(Collator.PRIMARY);
Collections.sort(list, myCollator);
itr = list.iterator();
System.out.println("");
while(itr.hasNext()) {
System.out.print(itr.next() + " ");
}

myCollator.setStrength(Collator.TERTIARY);
Collections.sort(list, myCollator);
itr = list.iterator();
System.out.println("");
while(itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}

And here is the result:
Où facil fast fácil ou specific spécifique êtes-vous
êtes-vous facil fácil fast Où ou specific spécifique
êtes-vous facil fácil fast ou Où specific spécifique

First one is the normal sorting, second and third is Collator sorting with 2 different types. You can very easily see that we are giving respect to other locale as well in sorting. There are 2-3 line comments in the code, which will tell which all locale Collator is supporting.

Sunday, January 13, 2008

MyClassLoader - Java ClassLoader Final Part

Sorry as I am not able to proceed sequentially. But now its time for implementation. I have 3 java files with me:

1. myClassLoader.java which inherits from ClassLoader and implements the minimum requirement.

2. myClassLoaderMain.java which loads the class HelloWorld, making its instance and calling one of the method of it.

3. HelloWorld.java which is simply a program with one method.

myClassLoader is not doing any of the special job but at the end I am providing you the link of some more documents which can provide you special classLoader like one good article is showing you how to load class change on fly.

myClassLoader.java

import java.io.*;
import java.util.*;
public class myClassLoader extends ClassLoader {
private Hashtable classes = new Hashtable();
public myClassLoader(){
super(myClassLoader.class.getClassLoader());
}
public Class loadClass(String className) throws ClassNotFoundException {
return findClass(className);
}

public Class findClass(String className){
Class result=null;
result = (Class)classes.get(className);
System.out.println("Class Name is : " + className);
if(result != null){
return result;
}
try{
return findSystemClass(className);
}catch(Exception e){
return null;
}
}
}

myClassLoaderMain.java

public class myClassLoaderMain {
public static void main(String [] args) throws Exception{
myClassLoader test = new myClassLoader();
Object o = (test.loadClass("HelloWorld")).newInstance();
((HelloWorld)o).mymethod();
}
}

HelloWorld.java

class HelloWorld {
public void mymethod()
{
System.out.println("Atleast print this ");
}
public static void main(String[] args)
{
System.out.println("Hello World");
}
}

Now running all together:

javac *.java
java myMainClassLoader
/* It will call mymethod of HelloWorld */

If you are keen to move further and want to make some magical class Loader please check this articles:
1. Basics of ClassLoader on JavaWorld.
2. A look at Java ClassLoader - Here they made an example of loading class at runtime.
3. Java ClassLoader wiki page.

Any comments or correction or questions are most welcome.

Inheritance and Memory Retention Issue with Finalization

Finalization is mostly used in Java to reclaim resources, native resources. Say, you are writing one program and you are using Windows Font(OS font). So, its the programmers duty to reclaim the font resource associated with any object.

If you are an application developer and uses lot of native resource then I would say stop reading this blog and read the latest Article(yes, Sep 2007) by Tony Printezis on sun site. This article is awesome and covers all the cases and its solution that can happen with Memory Retention. The simplest of that is what I am going to talk here.

Now, consider an example :

class PlayWithFont {

String someText;
String newText;

private native method getFont();
void get() { getFont(); }

// private because its a native method and always be called by any method of this class only
private native method releaseFont();
void release() { releaseFont(); }
protected void finalize() { release(); }

}

Now, here I have some text and I am taking OS font, converting that text into some fancy text and then releasing the resource of Operating Systems.
We have a class called PlayMoreWithFont which basically inherits PlayWithFont and converting some String[] text into new String[] text (just a fictitious example)

class PlayMoreWithFont {

String[] someMoreText ; // lets consider it here some big chucks of memory
String[] newMoreText;

}

PlayMoreWithFont don't have any finalize method defined, but off course its going to take one from PlayWithFont.

GC maintain a finalization queue. When a object is unreachable, object is added to the finalization queue. After that only object goes into finalized state. Now when we called :

play = new PlayMoreWithFont;
play = null;

Now instance of PlayMoreWithFont become unreachable, but reclamation of big chunks like someMoreText and newMoreText has to wait until the instance is finalized. And this is one of the major causes of memory retention. Moreover the problem is difficult to find if the class hierarchy is very deep and finalize is sitting some where very deep.

There are some good solution which we can discuss in next.

Wednesday, January 02, 2008

MyClassLoader - Java ClassLoader - Part 2

MyClassLoader will take one more entry for completion. Before writing our own custom ClassLoader, we have to devote sometime to see the methods of ClassLoader. Some of them need special attention while others we can ignore. Before starting with methods, we can see some type of ClassLoader available in jdk(openjdk) itself. AppletClassLoader, RMIClassLoader, SecureClassLoader, URLClassLoader are some of them. Remember all the custom ClassLoader need to extend ClassLoader except one :-). Any guesses ? Bootstrap Class Loader - Yes, this is responsible for loading runtime classes(rt.jar- very famous jar file in /jre/lib :-) ) . It has a native implementation and hence varies across JVM. So, when we write

java MyProgram

Bootstrap ClassLoader comes into the action first.

Alright, back to methods: we can see the whole list of methods of ClassLoader here. But we will see those of our interest:

- loadClass -> entry point for ClassLoader. In JDK 1.1 or earlier, this is the only method we need to override but after JDK 1.2 some dynamics get changed. Will discuss that later.

- defineClass -> As I mentioned in the last blog, this is one of the complex method which takes raw data and turn it into Class Object. Need not to worry, it is defined as final(so we can't change... who want to change).

- findSystemClass -> looks for the class file in local disk, if yes calls defineClass and convert the raw data into Class Object.

In JDK 1.2, new delegation model came into picture where if ClassLoader can't able to find a class, it asks (it's) parent ClassLoader to do it. JDK 1.2 came up with a new method called findClass which contains specialized code and help you when you are messed up with lot of ClassLoader. So, from JDK 1.2 and onwards, we just need to override findClass and everything will work fine, if not it will throw ClassNotFoundException. There are lot of other methods like getParent, getSystemClassLoader, but we can write our custom ClassLoader without touching these methods.

So, top skeleton looks like:

public class MyClassLoader extends ClassLoader {

public CustomClassLoader(){
//getClassLoader returns ClassLoader
super(CustomClassLoader.class.getClassLoader());
}

}

//lot of thing after this

Tuesday, January 01, 2008

MyClassLoader - Java ClassLoader

I am very new to Java and often terms like ClassLoader, Virtual Machine scares me before start. With little of courage I start reading some of the documents on ClassLoader and ahh I find it very simple. Actually with reply to some of my old blog's comment, we had made a statement that "you can have your own classLoader in java".

The good part about ClassLoader - its written in Java :-). So one can expect code to be simple and more understandable than written in C++.

ClassLoader is nothing but a part of Java Virtual Machine responsible to load classes into memory. From where ? From local hard drive(mostly), from network and in some cases from browser. Little complex yet beautiful part of it is it load classes on demand not all at once. Java has an excellent feature to write your own classLoader which extends to ClassLoader class. Here, I named it as MyClassLoader :-). But if JVM has a classLoader why to write another one ? In my case, just for fun :D but there are other uses. One I got, is to automatically verify digital signature before invoking untrusted code. Second and more important when you want to update class at runtime. So, in this case we need to create another instance of our classLoader and then we can replace the already loaded classes with new updated classes. We can see some other usages as we move on to the blog.

I start reading some code here and there of classLoader from openjdk. If you have openjdk on your system, I will better suggest to go through some of the API implementation of ClassLoader. You will get the ClassLoader.java at path \jdk\src\share\classes\java\lang\ClassLoader.java. I was surprised to see that very less changes has been made to this file after jdk 1.2 and a great enhancement is done on jdk 1.2. In the code, you can see most of the API's have written in 1.2 only.

When java got released the most exciting and eye catching feature is how it execute code on the fly from remote server. Some kind of magic ? Yes, this magic is possible because java has the ability to write a custom classloader. The magic is this - in appletviewer/browser instead of looking into local had disk for classes it looks for remote server, loads the raw data through http and turns them into classes(duty of method called defineClass in ClassLoader, we will see this in more detail) inside Virtual Machine.

I am still in the midway of many document, reading re-reading and trying to understand more of it. We will try to see some of the method(s) which we need to implement for our custom ClassLoader, MyClassLoader. Most of the methods sounds easy but some methods like defineClass which is actually converting raw data into classes may go little complex.

Sunday, December 23, 2007

jhat - Java Heap Analysizer

Since I get involved in some jhat related project with one of my senior team members. I decided to make some blog entries. jhat is java heap analysis tool which is shipped in jdk6. There is an independent project name hat on hat.dev.java.net. jhat is flavor of this project only.

If you are a guy, who write lot of Java code and keep on looking for optimization, if you are getting errors like memory overflow.. then yes its a tools for you only.

jhat is all about giving readable information from java heap dump. Java Heap Dump contains information like how many classes, how many instances, execution flow and many more.
But all these information are in a binary format. And the duty of jhat is to read that file and provide useful information to you.

There are lot of ways to generate heap dump:

1. From normal java execution program, you can see the heap by Ctrl + Break.
2. jdk6,5 is coming with some tools like jmap, jconsole which help us to generate heap dump. Usages of these tools are very easy.
3. jdk5 also comes up with a tool called HPROF which can be used to generate heap dump.

So, here are the steps, how to approach the problem:

Make heap dump with jmap:

1. Run the java program, say SwingSet2 in the example.
2. Open other terminal, and run jmap
jmap -dump:format=b,file=heap.bin (On Windows, you can get pid by Ctrl-Alt-Del -> Process -> PID )

jmap will generate a file with name heap.bin which contains heap dump. Now pass this heap.bin to jhat.

3. jhat heap.bin

There are lot many optional argument, check the detail here.

Open browser, type: http://localhost:7000 (7000 is the default port), you can see hell lot of information. Grab the information of your interest. Or if you want to parse the information from yourself use OQL(Object Query Language) and write query.

Sunday, December 09, 2007

How Java handles Method ?

In my previous blog "Performance - Final Keyword ? " One of the blog readers asked question about How Java handles overriding ! So, I decided to make one entry(I guess more than one) for the answer.

Yes overriding tactics in Java is very different from C++ as methods by default in Java can be overridden unlike C++. In C++, the concept of overriding functions are handled by Virtual Table, VTable(This wiki link contains lot of information). Whereas in Java there is some other concept. Before going into the depth, let's see some of the basic things which one should need to know before making hand dirty in overriding concept.

Here is a Simple HelloWorld Program:

class Hello {
public static void main(String[] args)
{
System.out.println("Hello Bloggers!");
}
}

Lets see what the bytecode is generating, javap -c Hello(more about javap)

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

public static void main(java.lang.String[]);
Code:
0: new #2; //class Hello
3: dup
4: invokespecial #3; //Method "":()V
7: astore_1
8: getstatic #4; //Field java/lang/System.out:Ljava/io/PrintStream;
11: ldc #5; //String Hello it is
13: invokevirtual #6; //Method java/io/PrintStream.println:(Ljava/lang/Str
ing;)V
16: return

}

Have a look on these lines:

1: invokespecial #1; //Method java/lang/Object."":()V
4: invokespecial #3; //Method "":()V
13: invokevirtual #6; //Method java/io/PrintStream.println:(Ljava/lang/Str
ing;)V

These are the lines related to method invocation. So what the heck is this invokespecial and invokevirtual ? Actually JVM used 4 different kinds of instructions for method invocation those are :

- invokevirtual - This is for instance method like System.out.println("Hello Bloggers!") here.
- invokestatic - This is for class methods.
- invokespecial - This is for special things. It is used when
- call , instance initialization.
- super call, when you will call something from super.method
- private methods. As private methods can't be overridden so we need to put this in a special category.
- invokeinterface - invoking instance method with interface reference(Soon we will see the example)

Now we are very clear that why invokespecial has been used at #1 and #3 whereas invokevirtual at #6. Ok, lets write some code which can see the usages of all four.


interface interfaceForHello {
public void noUse();
}

class Hello implements interfaceForHello {
public void noUse() {
System.out.println("No use");
}
public static void staticMethod()
{
System.out.println("Static method");
}
public static void main(String[] args)
{
interfaceForHello iface = new Hello();
iface.noUse();
Hello.staticMethod();
System.out.println("Hello Bloggers ! ");
}
}

And here goes the javap -a Hello:

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

public void noUse();
Code:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3; //String No use
5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return

public static void staticMethod();
Code:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #5; //String Static method
5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return

public static void main(java.lang.String[]);
Code:
0: new #6; //class Hello
3: dup
4: invokespecial #7; //Method "":()V
7: astore_1
8: aload_1
9: invokeinterface #8, 1; //InterfaceMethod interfaceForHello.noUse:()V
14: invokestatic #9; //Method staticMethod:()V
17: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
20: ldc #10; //String Hello Bloggers !
22: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
25: return

}

In next blog we will continue the same.

Saturday, December 01, 2007

OpenJDK Build on Netbeans with Windows / Solaris - Part II

Talking of some of the details about OpenJDK building(on Netbeans), we can start with Windows build(x86). In general,building on windows is tougher than Solaris/Linux because there are lot of dependencies on other tools and we can't set up the tools on network. Now lets see the list of the downloads required (don't abuse me, I know its too much :-))


- OpenJDK - Download open source JDK

- Binary Plugin - Download Binary Plugin

We need to install binary of Java SE 6, which we can get from Sun site and Java SE 7 which we can download from http://download.java.net/jdk7/binaries

Now this is all about JDK downloads. Time to put hand into the dirty world of other dependent tools:

1. As we have lot of C++ code(native code) inside JDK, we need a C++ compiler. For windows, JDK document suggests to use .NET2003. Though we have made the build on .NET 2003 but I guess compiler of .NET 2003 is free on net and you can give one try with free compiler. Note here: Don't try with .NET 2005 as many of the API get deprecated.

2. Cygwin Installation: This is a area of concern. We have invested(wasted :D) 90 percent of the build time in this tool. Installing, uninstalling, reinstalling .. and it keep on going. On the first installation page of Cygwin itself , you will get two options: Unix/Binary or Dos/Text. Any option can work, can't work depending on your luck :-). Most of the engineer suggested me to install Unix/Binary but Dos/Text worked for us :D. Download from: Cygwin Site

NOTE: Don't forget to download Developer, System, Utility, Archive package of its full mode not the default mode.

3. Install Microsoft DirectX 9.0 SDK(Summer Package) - Download it from Microsoft site

4. Download and Install FindBugs and Ant

5. Download Microsoft Unicode Library

6. Download and install latest version of freetype from www.freetype.org

7. Oops, if you don't have Netbeans 6 then download that also :)

Time to take a cup of coffee. Let the download to go on.

OK, back from coffee ...

Add Ant, Findbugs, Cygwin(till \bin) in the path variable of system. Open cmd, run vsvars32.bat (Micros~1.NET\Common7\Tools\vsvars32.bat) to initialize the .NET variables. Run Netbeans.exe from the same command line.

Open openjdk/jdk/make/netbeans/ in netbeans and open project jdk. Open some of the important file like build.propertied and make.xml. In make.xml file, you will get the path of make, change it to the cygwin make file {cygwin/bin }.

Now IMPORTANT, get ready to write build.properties file:

bootstrap.jdk={PATH_JDK7_INSTALL}
make.options=\
// this is important because code contains many
//line which work on if(OPENJDK==true) code
OPENJDK=true
// write the path in ~ format (dir /x)
ALT_COMPILER_PATH={MS.NET2003_PATH}/Vc7/bin \
ALT_MSDEVTOOLS_PATH= {MS.NET2003_PATH}/Common7/Tools/Bin \
ALT_MSVCR71_DLL_PATH= {MS.NET2003_PATH}/SDK/v1.1/Bin \
ALT_BOOTDIR={PATH_JDK6_INSTALL} \
ALT_BINARY_PLUGS_PATH={PATH_BINARY_PLUGS}
ALT_JDK_IMPORT_PATH={PATH_JDK7_INSTALL} \
ALT_DXSDK_PATH={DIRECTX_PATH} \
ALT_FREETYPE_LIB_PATH={FREE_TYPE_PATH}/lib \
ALT_FREETYPE_HEADERS_PATH={FREE_TYPE_PATH}/include \
ALT_UNICOWS_LIB_PATH={UNICOWS_PATH} \
ALT_UNICOWS_DLL_PATH={UNICOWS_PATH} \
LD_LIBRARY_PATH= \
CLASSPATH= \
JAVA_HOME= \
SHLVL=1 \


All Done ! Fire the build now, if you are lucky enough you will get it done in some 20-30 minutes. In the next blog, we are going to talk about the problem(s) with some of this software and version dependencies.

OpenJDK Build on Netbeans with Windows / Solaris - Part I

Our team is ready with OpenJDK build for FOSS.IN, better to say partially ready :). Me and Vikram is going to give the live demo about building OpenJDK and how you can optimize the source code according to your own need. For Example, if you don't like the default LookAndFeel of Java, change it according to your like because now its your world, its your Java. Let me show you one simple code change we have done with the gradient color. This is the normal Ocean LookAndFeel of Java.

Before the code Change:

After the code change:



Though building OpenJDK is little cumbersome process but come on, its a one time process. Just make the build ready once and then screw it as you want both on the Java level and on native level . Even more process and standard documents will come as OpenJDK goes into its maturity stage. You will love to know that Netbeans 5.5+ is giving a high class support for making OpenJDK across all platforms.

So for the real die-hard of Java, I am going to write Part II, III, ... upto N(covering some technicalities of building process) till I am not able to make you happy. Thanks to Igor and Sandeep who have replied my all shots of stupid questions.

Thursday, November 29, 2007

Performance - Final Keyword ?

Last night, me and Abhishek was discussing about some performance issue. Finally we came on a good conclusion and so I decided to write a blog. One of the Orkut users posted a question on our community

"As we know that by declaring method as final, we cant override them..........By performing this function, it provides a performance enhancement.........but i unable to understand how??????????? can anyone help me out...... "

(I don't know why people are using so many of dots and question marks)

Yes this is correct, writing final (can) improve the performance. Straight away question - WHY ?
When you define a method final, that means it can't be overridden into its derived classes. Knowing that into the fact complier (can) inline that method into its derived classes. But but but, this is not a safe way to inline a method. WHY AGAIN ?
Because, if by any chance if method will not be final (fool the VM) in base class, then inline entry in derived class will be wrong and things can be screwed. Now very rare but this is possible in Java. Remember in Java you can write your own classLoader and you can make a classLoader where you can ignore(any how) the final declaration.
So, for those compiler in which final method be inlined before loaded into VM(unlike JIT), there is quite a high risk and hence compiler can't do this. But in JIT compiler, this is what is happening ! (If you want to know more about JIT, please let me know :) ).

And this is how we finally ended our discussion :)

Sunday, October 21, 2007

SplashScreen for impatient Users :)

One more API in Java for those who are impatient in handling Java Application. A heavy application in Java takes time before starting up and hence JDK6 comes with a concept of SplashScreen. Its a simple class in JDK6 where user can show a screen on top of his application screen(before it getting start) that ,be patient, application will run in few seconds. Good part, it also supports gif image, so for completely impatient user who generally starts clicking here and there :D and screwing application, show a GIF image of progress bar.

It comes in various flavors:

- SplashScreen stay on the desktop till the main screen(application UI) will not come. Some polling or signal mechanism internally, I never bothered to see the code :D

- SplashScreen stay for given amount of time. A simple one.

Running is not an easy job. You have to define splash option with java

java -splash:imagename classname

I guess a good API for those who make games or some big application. One can give information like Copyright, Developer name, Loading..., Company name, etc etc. I mean generally for these information we waste one screen in our main application itself, why not use SplashScreen for that :).

You can see some sample code here:

http://www.devdaily.com/java/edu/SplashScreen/SplashScreenMain.java
http://java.sun.com/docs/books/tutorial/uiswing/misc/splashscreen.html

Wednesday, October 10, 2007

Java Font vs Native Font

So, here is one more problem of Java being machine independent. Font size depicts by Java Application will not be same as of Native Application, like if we consider Windows OS, native applications are MS office, Notepad and many more. Conversion from the size in points into device pixels depends on device resolution as reported by the platform APIs. Java 2D defaults to assuming 72 dpi.Platform defaults vary like Mac OS: 72 dpi, Linux/Solaris: 96 dpi, Windows: 96 dpi/120 dpi.So whenever you write a code for java font, be carefully of it's inconsistency with native application.

Look at this code, how to manage the font size on a particular platform(pretty simple)

import java.awt.*;
import javax.swing.*;

public class TextSize extends JPanel {
public void paint(Graphics g) {
Font font = new Font("Arial", Font.PLAIN, 30);
g.setFont(font);
g.drawString("Hello World", 25, 100);
Toolkit tk = Toolkit.getDefaultToolkit ();
int nativeResolution = tk.getScreenResolution();
final double javaResolution = 72.0; // java default is 72 dpi
Font font_new = new Font("Arial", Font.PLAIN, (int)Math.round(30.0*nativeResolution/javaResolution));
g.setFont(font_new);
g.drawString("Hello World", 25, 150);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
TextSize tx = new TextSize();
frame.add(tx);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}




















One can see the difference of Java and Native font size difference. The first "Hello World" is normal java code. Second " Hello World" is modified java code and third one is Native "Hello World". The staircase problem is also visible in Java Font, for removing that we can set ANTIALIAS_ON :-)

Friday, September 28, 2007

Synchronization - Wait a min.

Somewhere platform independence of Java fails when it all comes on Threading. Not a fault of Java because Threading means lot of dependency on system. How a particular OS is going to handling with your thread. Like if we see Windows NT, it doesn't support priorities of thread like priorities of Process, whereas Unix based system gives you the freedom to prioritize both thread and process.
Anyway, I am writing this article to just say that take care whenever you are writing any synchronized call. Every synchronized block or a method has an overhead and we can't ignore it. So before going to synchronization there is something called atomicity which means atomic operation like int a =2; luckily we never have to worry of threading issue in atomic calls. Its all thread safe. Again, take care x++ or x+=y is not falling under this atomic operation because there are two things going-increment and assignment.

Now, see the code here and also overhead of sync. call, which is of no use here:

import java.util.Date;

class ThreadCheck {

synchronized float uselss(int a, int b, int c)
{
return (a+b+(c/2));
}

float useful(int a, int b, int c)
{
return (a+b+(c/2));
}

public static void main(String[] args)
{
ThreadCheck threadcheck = new ThreadCheck();

//lets check the time
double begin = new Date().getTime();
for(int i=0;i<50000;i++)
{
threadcheck.uselss(4,3,2);
}
double end = new Date().getTime();
System.out.println("Time taken by Sync. call: " + (end-begin));

begin = new Date().getTime();
for(int i=0;i<50000;i++)
{
threadcheck.useful(4,3,2);
}
end = new Date().getTime();
System.out.println("Time taken by non-Sync. call: " + (end-begin));
}
}

This is the output I am getting:

E:\Program Files\Java\jdk1.6.0\bin>java ThreadCheck
Time taken by Sync. call: 16.0
Time taken by non-Sync. call: 0.0

One can clearly see a big overhead here. So the idea is just to take care while writing sync. block because threading is more in demand when we write real time systems and in RTS we can't afford such a wastage of time :).

Friday, September 21, 2007

Running Batch files in parallel

Yesterday night, one of my roommates got one problem. Actually his application demands to start 3-4 servers and all the servers has a startup.bat file. So, he actually want to write a code which can run those batch files. Now the problem here is he want to execute all those bat files in parallel. Note that a content of bat file always run sequentially. He was looking for any code which can do that, but we have selected java to do so :).

Runtime class has power to execute any batch file and threading concept has the capability to run batch files in parallel. So here goes the code:

import java.io.BufferedReader;
import java.io.FileReader;

public class BatchRunner extends Thread {

String msg;
public BatchRunner(String s) {
msg = s;
new Thread(this).start();
}

public static void main(String args[]) {
new BatchRunner("Hello");
}

public void run() {

String line = null;
Runtime r = Runtime.getRuntime();
try {

FileReader fr = new FileReader("D:\\Batchfiles.txt");
BufferedReader bufferedReader = new BufferedReader(fr);

while((line = bufferedReader.readLine()) != null)
{
r.exec(line);
}
} catch (Exception e) {
System.out.println("Error in Execution");
}
}
}

Batchfiles.txt contains full path of those batch files, which need to be executed. This is a fast solution and code must be optimized here.

Monday, August 06, 2007

Focus - lot to do ..

After JDK 1.4, there was a lot to see about focus in Java. Its one of the most interesting and challenging topics in AWT/Swing. JDK1.4 onwards there is one central class which takes care about the focus on components/windows KeyBoardFocusManager. Not only that, now you have freedom to write your own FocusManager.

This is one example where I tried to catch the focus lost and gain event on Focusable components.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class ButtonTest{

public static void main(String[] args)
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

class ButtonFrame extends JFrame {
public ButtonFrame()
{
setTitle("Button Test Frame");
setSize(LENGTH,WIDTH);
ButtonPanel panel = new ButtonPanel();
add(panel);
}

int LENGTH = 300;
int WIDTH = 300;

}

class ButtonPanel extends JPanel implements FocusListener {

public ButtonPanel ()
{

JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
JTextField text1 = new JTextField("Enter here");
add(button1);
add(button2);
add(button3);
add(text1);
button1.addFocusListener(this);
button2.addFocusListener(this);
button3.addFocusListener(this);
text1.addFocusListener(this);

}

public void focusGained(FocusEvent e) {
display("Focus gained", e);
}

public void focusLost(FocusEvent e) {
display("Focus lost", e);
}
void display(String prefix, FocusEvent e) {
System.out.println( prefix+" " + e.getComponent().getClass().getName());
}
}

If you are working on AWT or Swing , I would personally prefer to visit this article of JavaWorld:
http://www.javaworld.com/javaworld/jw-07-1998/jw-07-swing-focus.html

Saturday, July 14, 2007

Robot Class

Robot class is one of the most common classes used by guys doing automated testing. Giving some cool features to automate process. But still I find some thing lacking in this library or maybe I don't know how to use them.

Here I try to write a simple code, which write some text on a text editor and then close the editor without saving the file. Many things are hard coded in this example, like

robot.mouseMove(1420,20); // this is my desktop close button place in full screen mode.
So, if you want to run this code, just change this line according to your desktop. After changing run this code, open any editor say notepad within 10 seconds and then this example will write some text on it and then it will close the window.

import java.awt.Robot;
import java.awt.event.*;

public class MainClass {

public static void main(String[] args) throws Exception{


Robot robot = new Robot();
// giving you 10 sec to open any text editor.
robot.delay(10000);
robot.keyPress(KeyEvent.VK_T);
robot.keyPress(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_T);
robot.keyPress(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_T);


robot.mouseMove(1420,20);
robot.mousePress( InputEvent.BUTTON1_MASK );
robot.mouseRelease( InputEvent.BUTTON1_MASK );
Thread.sleep(50);
robot.mousePress( InputEvent.BUTTON1_MASK );
robot.mouseRelease( InputEvent.BUTTON1_MASK );
robot.delay(1000);
robot.keyPress(KeyEvent.VK_TAB);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_ENTER);

}
}

This is some useless example, but one can thing of some good examples but using this class.

Saturday, July 07, 2007

jikes vs javac

In my last post Priyanshu made a comment, " have you tried jikes". So, decided to give a try.

jikes is something which converts .java file into .class file. Yes, it is javac but IBM product not a Sun product. And let me begin with jikes page on sourceforge.net :

"You may wonder why the world needs another Java compiler, considering that Sun provides javac free with its SDK. Jikes has five advantages that make it a valuable contribution to the Java community:".

Providing free things, softwares and codes is a big deal for IBM but never for Sun. So don't keep on singing this Open source contribution song all the time. Whole world know what IBM is giving free.

So, advantage(s)

No. 1 : jikes is a open source software.
And so javac is ! Didn't get the advantage.

No. 2: Strictly Java compatible - It is not providing any superset or subset variation support.

Good, but this little of strictness most of time increase the code line from thousands or so.

No. 3: High Performance: Compilation is faster than javac.

Who really bother about compilation, anyway you have to come again and run on java command. I guess world is ready to devote 2 more minute in compilation.

Anyway, I have compiled one of the .java file(one which i have used in the last post) on the most stable version of jikes:

jikes TestForJDB.java

Issued 5 system warnings:

*** Semantic Warning: The file "E:/Program Files/Java/jdk1.6.0/jre/lib/ext/" doe
s not exist or else is not a valid zip file.


*** Semantic Warning: The file "E:/Program Files/Java/jdk1.6.0/jre/lib/ext/" doe
s not exist or else is not a valid zip file.


*** Semantic Warning: The file "E:/Program Files/Java/jdk1.6.0/jre/lib/ext/" doe
s not exist or else is not a valid zip file.


*** Semantic Warning: The file "E:/Program Files/Java/jdk1.6.0/jre/lib/ext/" doe
s not exist or else is not a valid zip file.


*** Semantic Warning: The file "E:/Program Files/Java/jdk1.6.0/jre/lib/ext/" doe
s not exist or else is not a valid zip file.

Didn't get what this warning message is and really not why you show it to me 5 times.

Then I have tried to look into -version command.

javac -version

- javac 1.6.0

jikes -version

- Jikes Compiler - Version 1.22 - 3 October 2004
Copyright (C) IBM Corporation 1997-2003, 2004.
- Licensed Materials - Program Property of IBM - All Rights Reserved.
Originally written by Philippe Charles and David Shields of IBM Research,
Jikes is now maintained and refined by the Jikes Project at:

Please consult this URL for more information and for reporting problems.

Very informative :)). Originally written by ... what does that mean ?



No 4. jikes provides some cool feature like incremental build.

I didn't get anything out of it.

Look at this feature.

jikes ++ TestForJDB.java

// After the 5 warning message.

Incremental: Enter to continue or q + Enter to quit:

nothing changed...

Incremental: Enter to continue or q + Enter to quit: (this if you change the code)

ok...

Incremental: Enter to continue or q + Enter to quit:

nothing changed...


No 5. clear error message.

I have removed one semi-colon from the code at line no. 25. Look at the error message printed by two compilers:

javac TestForJDB.java

TestForJDB.java:25: ';' expected
stringJDB = value
^
1 error

jikes TestForJDB.java

Found 1 syntax error in "E:/Program Files/Java/jdk1.6.0/bin/TestForJDB.java":

25. stringJDB = value
^---------------^
*** Syntax Error: ";" inserted to complete BlockStatementsopt

Are you able to find out something extra ? By the way what was the meaning of BlockStatementsopt ?


I guess I made too many of negative statement :), Ok some good features are here:

- it is providing some additional options like

> jikes +Punused-package-imports TestForJDB.java - which at compilation time, will show you those import statement which are not in use.

> jikes +Pnaming-convention testForJDB.java - it will throw warning if you are not following the naming convention ( its really an idea of Sun, don't mind :) )


Again, I didn't like the verbose information(javac -verbose filename.java) . Where is the time information man... parsing time, total time to make class file... these are some of the cool use of verbose option. Showing only which all files you are reading is a useless information.

Anyway, nice to see one step ahead in the world of open source.

Sunday, July 01, 2007

xjc.exe ?

Today I was looking some options in jdk/bin and suddenly I came across a file name xjc.exe in JDK6(I guess Mustang is no more official name of JDK6). Quickly I checked the existence of this file in JDK 5.0 and JDK 1.4.2. File was not present. Goggling didn't provided too much of help and I tried with myself :)

I just copied an XSD file from somewhere:

FileName: unknowntest.xsd (some problem with blogger, not able to take xml code :D, so pasting the image)










and passed this XSD file into xjc option:
Usage: xjc [-options ...] ... [-b ] ...

> xjc unknowntest.xsd

parsing a schema...
compiling a schema...
generated\Country.java
generated\ObjectFactory.java

Ah I got 2 Java files yeppp - Country.java and ObjectFactory.java
Look at these 2 files ( I am removing the documentation part of it, to make it small)

package generated;

import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"pop"
})
@XmlRootElement(name = "country")
public class Country {

@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected BigDecimal pop;

/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}

/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}

/**
* Gets the value of the pop property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getPop() {
return pop;
}

/**
* Sets the value of the pop property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setPop(BigDecimal value) {
this.pop = value;
}

}

and objectFactory don't have too much in it. Just creating a Country class instance. Oh so it is something cool, its making all the getter and setter method for me, what else I need :).

Remember, such type of methods are too much in demand when you are writing any jsp page. So, if you are clear with the data type, just make an xsd file and xjc will convert in into java code.

I still doubt what xjc refers for ... may be xml to java converter :)

Friday, June 29, 2007

Java Debugger

Since there is lot of high class debugger available with GUI, we never bother to use Debugger provided by JDK itself. Actually I also get to use of this someday back. Luckily lot of things available to use and some good options but some error message really wired you. But good if you want to look into those dirty threads and stack calls. Anyways lets try for some basics.

I have written a small code to debug(really don't have anything in the code to debug :) )

public class TestForJDB {

String stringJDB;

public static void main(String[] args)

{

TestForJDB test4jdb = new TestForJDB();

test4jdb.setString("test for JDB");

String getstring = test4jdb.getString();

String returnString = test4jdb.toString();

}

public TestForJDB()

{

System.out.println("Testing for JDB ");

}

public String getString()

{

return stringJDB;

}

public void setString(String value)

{

stringJDB = value;

}

public String toString()

{

return stringJDB ;

}

}


Now lets start jdb. Remember compile with -g option so that class file will get the debug informations.


E:\Program Files\Java\jdk1.6.0\bin>jdb TestForJDB

Initializing jdb ...

>

Putting some breakpoints. We have 2 ways either by line number or by method name.

> stop at TestForJDB:4

Deferring breakpoint TestForJDB:4.

It will be set after the class is loaded.

> stop at TestForJDB:11

Deferring breakpoint TestForJDB:11.

It will be set after the class is loaded.

> stop at TestForJDB:16

Deferring breakpoint TestForJDB:16.

It will be set after the class is loaded.

> stop at TestForJDB:20

Deferring breakpoint TestForJDB:20.

It will be set after the class is loaded.

> stop at TestForJDB:24

Deferring breakpoint TestForJDB:24.

It will be set after the class is loaded.


Now lets go ahead and run the class file

> run TestForJDB


It will show you some crappy information. Anyway, lets try to look into the methods available:


main[1] methods TestForJDB

** methods list **

TestForJDB main(java.lang.String[])

TestForJDB ()

TestForJDB getString()

TestForJDB setString(java.lang.String)

TestForJDB toString()

java.lang.Object ()

java.lang.Object registerNatives()

java.lang.Object getClass()

java.lang.Object hashCode()

java.lang.Object equals(java.lang.Object)

java.lang.Object clone()

java.lang.Object toString()

java.lang.Object notify()

java.lang.Object notifyAll()

java.lang.Object wait(long)

java.lang.Object wait(long, int)

java.lang.Object wait()

java.lang.Object finalize()

java.lang.Object ()


main[1] step

>

Step completed: "thread=main", TestForJDB.main(), line=6 bci=0

6 TestForJDB test4jdb = new TestForJDB();


Something unique to see here, bci = 0, what does that mean ? Don't know actually. BCI is Byte code Instrumentation and probably help if you want to go for native level debugging.


list command will tell you the current position of the debugger.

main[1] list

2 String stringJDB;

3

4 public static void main(String[] args)

5 {

6 => TestForJDB test4jdb = new TestForJDB();

7 test4jdb.setString("test for JDB");

8 String getstring = test4jdb.getString();

9 String returnString = test4jdb.toString();

10 }

11 public TestForJDB()


locals, a useful command will tell you the Methods arguments and local variable at that break point.


main[1] locals

Method arguments:

args = instance of java.lang.String[0] (id=331)

Local variables:


There are many other options like dump, step up which are useful for serious debugging. Quite Strange to know that such a tool was introduced in JDK 1.2. If you want to look into the architecture of JDB then visit this site: http://java.sun.com/j2se/1.5.0/docs/guide/jpda/index.html


Saturday, June 16, 2007