Wednesday Nov 25, 2009

Sorting and OpenJDK

If you are looking for sorting algorithms and if you use some sorting algorithm in your code/application/big application, then have a look here. First of all sorting/searching is a classic thing. It take more than 70 percent of your application time.People/Developer/Mathematician do a lot of work on optimizing this work to get Best, best out of best.

Early days, JDK used to use QuickSort which is one of the best sorting algorithm and go for a complexity of O(nlogn). But mind it, QuickSort is a recursive algorithm and consume space. Whereas some of the algorithm which has the complexity like O(n\^2) go for less complex in terms of memory. These days our platform varies from small mobile device to a terabyte storage machine............

[Read More]

Tuesday Jun 10, 2008

Avoid Array Sorting API for small list ?

All my personnel opinion, so can be wrong. But I have not found Array.sort very efficient for small lists and yes, it is not meant for small array list as well. I have written one small code where I have compared Sort API with the worst of all sorting algorithm, that is, bubble sort. Here is the code:

import java.util.\*;
public class BubbleSort {

	public static void main(String[] args) {
		int numbers[] = {10,20,5,14,1,56,0,56,56,3,2,5,466457,765,34,5,346,45676,23435,767,2545,62432,3,2,33,3,3,6,78,8,3435,7,3454567,35,50};
		int numbers1[] = {10,20,5,14,1,56,0,56,56,3,2,5,466457,765,34,5,346,45676,23435,767,2545,62432,3,2,33,3,3,6,78,8,3435,7,3454567,35,50};
		int length = numbers.length;
		long startTime1 = System.nanoTime();
		long endTime1 = System.nanoTime();
		System.out.println("Time taken in Sorting  : " + (endTime1-startTime1)+ " nanoseconds"); 
		long startTime2 = System.nanoTime();
		long endTime2 = System.nanoTime();
		System.out.println("Time taken in Sorting  : " + (endTime2-startTime2)+ " nanoseconds"); 

	public static void sortIt(int numbers[], int length) {
		int temp;
		for(int i=length-1;i>=0;i--) {
			for(int j=1;j<=i;j++) {
				if(numbers[j-1]>numbers[j]) {
					temp = numbers[j-1];
					numbers[j-1] = numbers[j];
					numbers[j] = temp;

	public static void showIt(int numbers[]) {
		for(int i=0;i<numbers.length;i++) {
			System.out.print(numbers[i] + "    ");
	public static void sortbyAPI(int numbers[]) {

This are very clear from output:

E:\\Program Files\\Java\\jdk1.6.0\\bin\\SoringPrograms>java BubbleSort

Time taken in Sorting : 90514 nanoseconds

0 1 2 2 3 3 3 3 5 5 5 6 7 8 10 14 20 33 34 35 50 56 56 56 78 346 765 767 2545 3435 23435 45676 62432 466457 3454567

Time taken in Sorting : 190527 nanoseconds

0 1 2 2 3 3 3 3 5 5 5 6 7 8 10 14 20 33 34 35 50 56 56 56 78 346 765 767 2545 3435 23435 45676 62432 466457 3454567

I have decided to check the code in OpenJDK(\\src\\share\\classes\\java\\util\\ And I find lot of interesting things there:

- The sorting algorithm is a tuned quicksort (written in the documentation)

- In the real code, for short array, Insertion sort has been used, for big array pseudomedian  and so many thing ..

- It means it should be fast for any sorting array, but not the case with me :-(. I am making any mistake ? Huh, need time to check the code !

Saturday Jun 07, 2008

Nominate OpenJDK, Netbeans !

Here it starts the nomination. Nominate OpenJDK for best project :). Is it not ?

Here goes the second nomination - Netbeans !

Saturday Mar 22, 2008

Final Variables

It can be little surprising but final variables can be changed from JDK 1.5 onwards. How ? Via reflection API. I still need to dig more into the code, off course OpenJDK code :) to see how it is possible. Here is a small code to see how final variable can be changed with reflection API:

import java.lang.reflect.Field;
class Sample {
final int finalInt ;
final String finalString ;

Sample(int a , String s) {
this.finalInt = a;
this.finalString = s;
public String toString(){
return(finalInt + " \*\*" + finalString);

public class FinalTest {
public static void changeFinal(Sample f, String finalString, Object value)
throws NoSuchFieldException, IllegalAccessException  {
Field field = Sample.class.getDeclaredField(finalString);
field.set(f, value);
public static void main(String[] args)throws Exception {
Sample ft = new Sample(10,"Hello World");
Searching little on Web explained me that this behavior is not consistent throughout. JDK1.2 used to give the same output for this code, whereas JDK 1.3 and 1.4 throws IllegalAccessException. And now again JDK 1.5, you can change the variable. I will try to see more on this part.

Monday Mar 03, 2008

Listing Java Process from Java

Month Ago, one of my colleagues was making an application, actually the UI flavor of JStack. Since JStack asks you the process ID for attaching the particular Java Application with JStack. In a UI based tool, telling user to do Alt-Ctrl-Del and see the process ID,not sounds good. So, my first impression was that you have to show the java process in the drop down and user will select in that. Some day back even, I want to find all process running on my machine from java code for some stupid purpose. I am trying to write some code for both of them. Java can't play with system process and hence invoking a runtime is only solution to get all process and here it is:

class ListProcess {
public static void main(String[] args)throws IOException
          Runtime runtime = Runtime.getRuntime();
           String cmds[] = {"cmd", "/c", "tasklist"};
           Process proc = runtime.exec(cmds);
           InputStream inputstream = proc.getInputStream();
           InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
           BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
           String line;
           while ((line = bufferedreader.readLine()) != null) {

Code is written exclusively for Windows Machine :). And one line change in this code will list you only java running process.

String cmds[] = {"cmd", "/c", "jps"}; this is nothing but running jps.exe file in bin (jdk6 onwards). Its not all done. Writting Runtime code is not the real solution as there is little of platform dependencies. So, I have decide to write the code for getting List of Java Process. Again, I have checked by OpenJDK code for jps(search on file :) ) and I got some hint how to do it and here it goes:

import java.util.\*;
import sun.jvmstat.monitor.\*;

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

    /\* Checking for local Host, one can do for remote machine as well \*/
          MonitoredHost local = MonitoredHost.getMonitoredHost("localhost");
    /\* Take all active VM's on Host, LocalHost here \*/
     Set vmlist = new HashSet(local.activeVms());
     for (Object id : vmlist) {
       /\* 1234 - Specifies the Java Virtual Machine identified by lvmid 1234 on an unnamed host.
       This string is transformed into the absolute form //1234, which must be resolved against
       a HostIdentifier. \*/
     MonitoredVm vm = local.getMonitoredVm(new VmIdentifier("//" + id));
       /\* take care of class file and jar file both \*/
    String processname = MonitoredVmUtil.mainClass(vm, true);
       System.out.println(id + " ------> " + processname);

I have written good amount of comment as it is all together a sun import rather than java or javax import. This import resides in tools.jar, so even running simple javac and java will not work. So, running the program will go here:

E:\\Program Files\\Java\\jdk1.6.0_10\\bin>javac -classpath "E:\\Program Files\\Java\\jd

E:\\Program Files\\Java\\jdk1.6.0_10\\bin>java -classpath .;"E:\\Program Files\\Java\\j
dk1.6.0_10\\lib\\tools.jar" Vista

3700 ------> ListJavaProcess

Right now only one java process is running. Now in the second code, you can play with some of the java process, but with native process in the above code you can't do anything except watching it :)

No idea how to do this in JDK 1.5 or backwards.

Thursday Feb 21, 2008

Mercurial on the way ...

Moving on to OpenJDK, mercurial is one big name we are hearing. It is similar to CVS or SCCS. A open source project. Vikram one of my team members has given yesterday one presentation on Mercurial. Have a look on his slides here. Slide speaks very basic of Mercurial and after reading this we can start of some of the basic mercurial operations.

Sounds very much faster than SCCS which we are using currently to bringover JDK Source Code. 



Saturday Feb 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 on different locale ? How it works 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);
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.print( " ");

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

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\\ Highly documented file.

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);
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.print( " ");

Locale[] loc = Collator.getAvailableLocales();

/\* for(int i=0;
Collator myCollator = Collator.getInstance(new Locale("fr"));
Collections.sort(list, myCollator);
itr = list.iterator();
while(itr.hasNext()) {
System.out.print( + " ");

Collections.sort(list, myCollator);
itr = list.iterator();
while(itr.hasNext()) {
System.out.print( + " ");

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

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.

Tuesday Jan 22, 2008

JTreg Convertor


Finally I reached on the verge to finish this tool. A simple tool
called "JTregConvertor". As I am already insisting to see OpenJDK and
here again. If you remember one of my blog entries, there is some
discussion on Jtreg. jtreg is nothing but a test suite for regression
test cases. Here we write/store all the testcases which can help code modifier(engineer) to check his code change. If his code change is causing some
problem somewhere say in area AWT, Swing, jtreg will fail that testcase and
hence you can get to know that this fix is not correct. But how jtreg
do this all. jtreg do this because the test case it runs is in a
special format called "jtreg format" which have some tags, some additional
classes and maybe some code changes with respect to normal test case.
Tags like which file to compile, in what order to compile, any applet
to run and many more.

See this part of the code in (openjdk\\jdk\\test\\java\\awt\\FontClass\\

 \* @test
 \* @bug 6533413
 \* @summary Test no crashing getting metrics using large font.
 \* @run main BigMetrics

This is the tags, we are talking off. You can check in any file in test folder. 

This UI tool is all about converting the simple
test case into jtreg formatted test case, so that developer need not to
break his head in knowing jtreg tags and classes.
Here are some snap shots of the tool :

Main Window

 Since code still have some bugs, so i am not putting it right now. Soon, I will do that with executable jar as well.

Wednesday Jan 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

//lot of thing after this

Monday Dec 31, 2007

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", I have started this blog entry.

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 at path \\jdk\\src\\share\\classes\\java\\lang\\ 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.

Friday Dec 07, 2007

OpenJDK Build on Netbeans with Windows / Solaris - Part IV

So its all done for Windows. Now coming on to Solaris, here the work is little less in compare to Windows(the same is valid for Linux as well, can be a excuse for me as I don't have Linux machine right now). Here is the list of downloads:

-> OpenJDK - Same link as mentioned in the previous blog (download the Solaris part, we have worked on Solaris x86)
-> Binary Plugin - Download from here.
-> CUPS Header - Download the latest cups from here.
NOTE: CUPS is Common Unix Printing System. It is doing a smart job of putting browser information into a printable format. I mean you don't have to worry about how printing is going to happen, it will be taken care by CUPS.
-> FreeType - Download from the same link provided in the previous blog. Any of the platform independent version will work for us.
-> jtreg - jtreg can be downloaded from the same link from where you are downloading OpenJDK. jtreg is a test suite that contains tons of testcase. Responsibility is to write a safe code and code change will not screw anything.

Thats it ! I am assuming that you have Netbeans 6+ and JDK 1.7 and JDK 1.6 binaries installed with you.

Now setting the file. Its very small in comparison to windows. Here it is:

// this is important because code contains many
//line which work on if(OPENJDK==true) code
OPENJDK=true \\

All done. Time to fire the build. More likely you will face the same problem what we have mentioned for Windows. If you are lucky enough then you will get the message "BUILD SUCCESSFUL"
(If I missed some step, please follow as it is in previous blog)

Sunday Dec 02, 2007

OpenJDK Build on Netbeans with Windows / Solaris - Part III

Now if you all set according to the last blog. This is/are the possible error(s) :

1. Error in make file : Multiple target \*\*\* . Yes, you need to downgrade the version of make file. "make.exe" resides in /cygwin/bin/make.exe. Check out its version, if its not 3.80, time to downgrade it. Download from here. Replace the make.exe of cygwin with this new make.exe ( make -version should be 3.80).
NOTE: make.exe is responsible to run make files. Makefiles are the one which contains instructions for a specific project, which file to compile and in which order.

2. Compilation error in - Try out Igor's solution
NOTE: Cygwin(make of Cygwin) still have some problem in understanding \\r character. So, this error may go with the upcoming binaries of Cygwin. One way is just remove \\r from the sh file - But then you will not get the proper file.

3. freetype.dll not found: Yes, freetype installation is  not creating any file like freetype.dll and this is surprising. If you investigate properly, you will get one file with name freetype.dll.a. Right now, lets rename it to freetype.dll(later we will check the problem of renaming this file)
NOTE: Just one line about freetype, it is providing uniform interface to access font files, support anti-aliasing as well.

4. I guess this is the main three error we came across. If anything else coming, then you need to check the installation of Cygwin again.  Errors like zip or tar.exe not found, means you have not installed the archive package of Cygwin.

Now if you are lucky enough, all things go fine and build will be ready. Again note that, jdk project module of Netbeans is only responsible for j2se build which mostly contains Java API not containing hotspot part. So, check the javac.exe and java.exe of your own openJDK build in the folder /openjdk/windows-i586/bin/.

5. Give a try to your Program. Ah it is running :-) cool. Now give a try on in which you are creating a Frame. If unluck you will get this error: not a proper dll file: freetype.dll. So, renaming is not actually working which we did in Error 2. Actually .a is a library achieve which is not a proper  file at this point. So, what to do ? Either find proper freetype.dll file from somewhere or take the source of freetype and compile it on .NET according to these rule.

Now its all yours. If you get any additional error, please let me know via comment or drop me a mail


Saturday Dec 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

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

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 file:

// this is important because code contains many
//line which work on if(OPENJDK==true) code
// write the path in ~ format (dir /x)
ALT_COMPILER_PATH={MS.NET2003_PATH}/Vc7/bin \\    
ALT_MSDEVTOOLS_PATH= {MS.NET2003_PATH}/Common7/Tools/Bin \\
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.

Friday Nov 30, 2007

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 Nov 29, 2007



Sun is ready for the big event FOSS.IN going to happen in Bangalore, India. Our J2SE team is going to give two demo. One is about OpenJDK and other is all about JavaFX, the new cutting edge technology. Both underwent through the dry run before the actual event occurs. We are ready with OpenJDK build on Win32 and off course Solaris. Without too much of the change Solaris scripts files can be mapped on Linux as well. If anyone of the blog reader(s) are interested in making build of OpenJDK, the please leave a comment or just drop me a mail. Thanks for Igor Nekrestyanov and Sandeep Konchady to provide lot of help.

We have made the build from command line and from Netbeans 6 both. Still lot of things to do :-)


Vaibhav Hi, I am Vaibhav Choudhary working in Oracle with JDK team. This blog is all about simple concept of Java, JVM and JavaFX.


« June 2016