w3hJava

What, Why, When and How of Java, JavaFX and related technologies

June 9th, 2008

How Java handles overriding

One of the blog readers recently asked a question about “How Java handles overriding !”  So, I decided to make one entry 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 their hands 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

}

June 4th, 2008

Final can improve performace !

Last month, 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. 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 !

In 2 line, I want to write about JIT(Just in time compiler) - at the time of interpretation,interpreter saw there is a for loop, for say 50 times. It takes the code out from interpreter and give it to runtime compiler(c1 and c2 compiler). As we know compilation is faster than interpreter. Compiler do the work and then control goes back to Interpreter. Details are quite interesting.

And this is how we finally ended our discussion :). Correct me if I am wrong.

In next post, we will discuss how to write a custom ClassLoader.

May 28th, 2008

Multi-threading in Java

One of the greatest features in Java is support for multi-threading. Generally we have misconceptions about the concepts of threading. We tend to think it more as a part of coding and hence take it only at coding time. Threading is all about designing and not about coding. If you want to write a good threading code, think of it before writing the code. Sometime back, I had made a presentation on multi-threading in Java with some demos. Have a look here :)

here

Presentation is very basic and talk simple things. Your comments are most welcome.

May 23rd, 2008

Java - Pass by Reference(Not possible)

I had a big time fight on my Orkut community with the concept that Java do things with Pass by Reference. Here is the one for Orkut users :

Here

But for non-orkut users let me recap the point again, its very important for a person who is new in java:

There is NO CONCEPT OF CALL BY REFERENCE IN JAVA, ONLY CALL BY VALUE IS POSSIBLE. We generally get confused in pass the object reference by value and passing by reference. Both are completely different.

Here is a small code, to get a more clear picture:

class MyClass {

String name;
int nameCode;

public MyClass(String name, int nameCode) {
this.name = name;
this.nameCode = nameCode;
}

public String toString() {
System.out.println(name + " : " + nameCode);
return (name + nameCode);
}
}

public class NoCallByReference {

public static void swap(MyClass a, MyClass b) {
MyClass temp = a;
a = b;
b = temp;
}

public static void main(String[] args) {
MyClass myclass = new MyClass(”Ramu”, 7);
MyClass yourclass = new MyClass(”Mohan”, 1);
swap(myclass, yourclass);
myclass.toString();
yourclass.toString();
}
}

A very simple code where I tried to swap two object of myClass. But you will surprise to see the output because after swapping even the value of myclass and yourclass will remain the same. Because the copy of myclass and yourclass has been created and get swapped rather than actual myclass and yourclass. It’s like

myclass — copyofmyclass
yourclass — copyofyourclass

Swapping is done on copyofmyclass and copyofyourclass. Better to go for a homework and run the command

javap -c NoCallByReference and try to figure our how assemble is going on :-).

May 18th, 2008

Memory Retention

Finalization is mostly used in Java to reclaim resources, native resources. Say, you are writing one program 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.

class PlayWithFont {
String someText;
String newText;
private native method getFont();
void get() {
getFont();
}
// 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 big and finalize is sitting some where very deep. There are some good solution which we can discuss in next.

May 16th, 2008

Is Compiler Optimization always good?

Last week, I made a presentation on Multi-threading in Java. Although I had covered this aspect in presentation but still wanted to blog more on the same. In multi-threading world, compiler optimization can cause serious problems. Check out this small piece of code

public class NonVolatileProblem extends Thread {

    ChangeFlag cf;

    public static void main(String[] args) {
        ChangeFlag cf = new ChangeFlag();
        NonVolatileProblem th1 = new NonVolatileProblem(cf);
        NonVolatileProblem th2 = new NonVolatileProblem(cf);
        th1.start();
        th2.start();
    }

    public void run() {
        cf.method1();
        cf.method2();
    }

    public NonVolatileProblem(ChangeFlag cf) {
        this.cf = cf;
    }
}

class ChangeFlag {

    boolean flag = false;

    public void method1() {
        flag = false;
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            System.out.println(”Don’t want to be here”);
        }
        if (flag) {
            System.out.println(”This can be reached “);
        }
        System.out.println(”Value of flag” + flag);
    }

    public void method2() {
        flag = true;
    }
}

Check out the reason in bold. Now if compiler optimizes the code and remove the part of if(flag), thinking that flag value will always be false. Then we have a situation here(FBI style of speaking :-D), because other thread can change its value and can make the flag value true.

Try to run this code 5-6 may be 10 times, you will be able to see the SOP statement “This can be reached“. Just for te sake of getting that, I have added sleep statement. Here what I got on my 3rd run of the code :)

Value of flag:false
This can be reached
Value of flag:true

Handling such type of situation is not difficult, specification says to add a word volatile before the variable flag which will tell the compiler not to optimize its code just by seeing some initial value or declaration.

May 13th, 2008

Listing Process from Java Code

A month back, I wanted to find out all processes running on my machine from java code for some stupid purpose. I tried to write some code and was pretty successful. Java can’t play with system process and hence invoking a runtime is only solution to get all process and here it is:

import java.io.*;
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) {
            System.out.println(line);
        }
    }
}

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. Writing Runtime code is not the real solution as there is little of platform dependencies. So, I have decided to write the code for getting List of Java Process. Again, I have checked by OpenJDK code for jps(search on jps.java 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\jdk1.6.0_10\libtools.jar" ListJavaProcess.java
E:\Program Files\Java\jdk1.6.0_10\bin>java -classpath .;"E:\Program FilesJava\jdk1.6.0_10lib\tools.jar" ListJavaProcess
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(runtime is off course one option).

May 11th, 2008

Number of JREs on my Windows machine?

Sometime back, we were discussing something about JRE and one of my friends Lawrence asked me “How to find the number of JRE  installed on system with the help of Java Code ?

After giving much thought to it, I don’t think Java has any such API which will tell how many JRE are installed on the System and what are they ? One of my another friend Vikram told me that JRE installation records information in Registry. With this knowledge at the hindsight, I tried to write this piece of code.

It will only run on Windows :) because I have used Runtime class. I would love to know how the same could be achieved in Unix Systems. This code is not doing anything great, just queries the registry and reflects the answer on the console.

import java.io.*;
class NoofJRE {
    static String REG_PATH = "reg query " +
                          "\"HKLM\Software\JavaSoft\Java Runtime Environment";
       public static void  getJREInfo() {
            try {
            Process process = Runtime.getRuntime().exec(REG_PATH);
                  InputStream inputstream = process.getInputStream();
                  InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
                  BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
                  String line;
                  while ((line = bufferedreader.readLine()) != null) {
                           System.out.println(line);
                  }
          }
            catch (Exception e) {
                  System.out.println("I am in Exception");
        }
      }
      public static void main(String s[]) {
            getJREInfo();
        }
}

And here is my output:

E:\Program Files\Java\jdk1.6.0\bin>java NoofJRE
! REG.EXE VERSION 3.0
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment
CurrentVersion REG_SZ 1.6
BrowserJavaVersion REG_SZ 1.6.0_01
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.4.2_17
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.6
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.6.0
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.6.0_01

Which sounds true in my case. It is clearly telling me that I have JRE 1.4.2_17, 1.6.0 and 1.6.0_01. I have old bad habit of not uninstalling JRE’s :).

Please do let me know if there is any other way to know how many and which JRE is/are installed in my system.

To know where the JRE is installed, one has to do a simple query of JAVA_HOME in the registry.

May 9th, 2008

Sorting different Language(Locale) in Java

I have given a little thought what should be my first post. Finally decided not to write anything complex. I am just posting about simple sorting fundas in Java. Sorting is always a tricky game in any programming language and it is responsible for 50-60 percent of the total CPU time for any application. We all have our native language like Hindi, Chinese, Japanese, French and so many. Most of the time world deals with sorting of Alphabets or English words but give a eye on other languages which is growing fast and off course today we are talking about internationalization.

I am showing you a typical sorting of French word and the blunder associated with it. These are some of the common French words:

String[] names = {”fácil”, “facil”, “fast”,”Où”, “êtes-vous”, “spécifique”, “specific”, “ou”};

and here is the typical sorting code:

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

which is completely wrong according to French Rules. Because sorting is simply going via UNICODE rules not by French rules.

Now remedy: Java gives us a class called Collator class in java.text Package which takes care of locale while sorting. Here goes the 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();
        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

which is perfectly valid. There are lot of option in Collator class which we will discuss sometimes later here only.