w3hJava

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

June 28th, 2008

BOJUG Talk and Presentation

Last Friday, I have given a talk on Java SE 6u10 features in BOJUG meet. Here is the presentation.

These slides basically talks about Java SE 6u10 features. Some of them are cool like

-> Next Generation Plugin where you can drap plugin outside the browser.

-> Kernel JRE. Download small JRE.

-> Nimbus Look And Feel

-> New Applet feature which we talk in prev. blog.

And many more.

Please provide your comment on the presentation.

June 21st, 2008

How to use JDK 6 to solve memory issues?

Take care of disk space when you are writing a big program :). Use JDK 6 features:

import java.io.File;

public class DiskSpaceCheck {
public DiskSpaceCheck() {
File file = new File("E:");
System.out.println("E:");
System.out.println("Total:  " + file.getTotalSpace());
System.out.println("Free:   " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());

file = new File("E://movie");
System.out.println("E://movie");
System.out.println("Total:  " + file.getTotalSpace());
System.out.println("Free:   " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());

file = new File("/");
System.out.println("n/");
System.out.println("Total:  " + file.getTotalSpace());
System.out.println("Free:   " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());
}

public static void main(String[] args) {
new DiskSpaceCheck();
}
}

I was actually very suprised that why this feature came so late.

June 17th, 2008

Test your applet on different JRE’s

In last post on StringBuffer, Dimitris Andreou commented that it was an old thing. ;-). So, I decided to write something new which is currently going on in Sun Microsystems. Finally I zeroed down on Java SE 6u10 features. Some of them I blogged on my Sun site but here are some more.

Very often this happens. You made a UI in applet and want to check whether the application is working fine on all JRE’s or not. If you are not, then please do it :).?I have seen people still using JDK 1.3. I, myself use jdk1.4.2 for many reasons and it still survive somewhere in the company standards. Now, if you want to check the applet on all JRE’s, welcome to the world of JRE 6u10 features.

Here is the demo:

Write a normal applet code, say Hello World.

import java.awt.*;
import java.applet.Applet;

public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World",50,50);
} // end of paint
} // end of applet

And now the interesting part, write the HTML file like:

<APPLET CODE="HelloWorld.class" WIDTH=200 HEIGHT=100>
<PARAM name="java_version" value="1.5.0_20">
</APPLET>

It will run the applet on JRE 1.5.0_20(if exists on machine). For more generic once, write:

<APPLET CODE="HelloWorld.class" WIDTH=200 HEIGHT=100>
<PARAM name="java_version" value="1.4*">
</APPLET>

It will check any flavor of 1.4 like 1.4.2_01 or 1.4.2_10 on your machine. 6u10 rocks ! Remember it will work in IE6 or + and FF3 or +. Ah, I remember, today is FF3 download day. So, please don’t forget to download FF3.

June 15th, 2008

String goes StringBuffer

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

I was reading one of the posts of orkut Java community asking “what is this capacity in StringBuffer and even we can add two strings from String class why to go for StringBuffer”. Valid question ! GC need to work little more in case of String, but thats fair.

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

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

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

Alright, now have a look on the bytecode of this program.

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

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

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

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

>> javac -verbose StringTest.java

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

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

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.