Java

How Java uses StringBuilder class for Byte code optimizations ?


We all know Strings in java are immutable. This means that whenever we modify a String, it creates a new String object with the modified value and throws the old one away (of course, If there are no other references to it). Hence concatenations using Strings are expensive, consuming both time and memory.The obvious solution is to use the StringBuilder Class which is not immutable.

No StringBuilder, it’s still fine !!

But does this mean that we need to explicitly use StringBuilder objects in java code ? Consider the following example.

int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6;
String s = "String Concatenation Example" + a + b + c + d + e + f;

Considering the immutability aspect of String, how do we expect the java runtime to execute the above example ? First it would have to create a String object with value "String Concatenation Example". Then it would create another string with the value of variable 'a' appended to the first one and then throw away the string object created initially (ie makes it eligible for garbage collection). This process of creation and throwing away would be repeated until all the variables mentioned in the statement are appended.

Well, if you thought that that is how it works. Then you are wrong. Starting from Java 1.6.x, the java compiler does some byte code optimization to handle this in a different way. To find out, i used a decompiler to decompile the bytecode (.class file), and this is what i found.

int a = 1; int b = 2; int c = 3; int d = 4; int e = 5; int f = 6; 
String s = (new StringBuilder("StringConcatenationExample")).append(a).append(b).append(c).append(d).append(e).append(f).toString();

The Java compiler, finding that developer uses String.concat() or + to concatenate multiple strings, optimizes the code during compile time and replaces it with a StringBuilder object.

What this means is that the java compiler lets us use the conventional way of string concatenations ( thus retaining the readability of the code ), but works in the background during compilation to implement these concatenations using the StringBuilder object thus saving on both memory and time for these computations.

Where i really need the StringBuilder !!

Now,can we assume that we can use conventional string concatenations ( using string.concat or + ) in all constructs and expect the compiler to do the optimization for us. Well, Think again !!

Consider the following example.

String s = "";
for (int i = 0; i < 100; i++) {
   s += i;
}

On decompilation, this gives

for(int i = 0; i < 100; i++) 
   s = (new StringBuilder(string.valueOf(s))).append(i).toString();

Here the compiler does convert the concatenation operation to a StringBuilder. However, it creates a new StringBuilder object for every iteration of the loop which obviously is a waste of memory. The better way to code this would be :

StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 100; i++) {

	stringBuilder.append(i);
}
System.out.println(stringBuilder.toString());

Some Thumb Rules !!

Hence the thumb rules to be applied here are, for regular constructs, use conventional String concatenation, for it’s readability and when performing String concatenations within loops, use the StringBuilder class.

The Maven Integration requires that Eclipse be running in a jdk [solved]


MavenEclipseException

What do you do when you get this Exception in Eclipse ?

Answer : You need to add/edit the eclipse.ini file in your $ECLIPSE_HOME ( if you have one ) or the default one in your Eclipse installation directory with following details.

-vm
/home/user/java/jdk1.6.0_33/bin/java

Add the -vm option before the -vmargs option. Of course the exact location of your java will be different! For more on eclipse.ini, go to the eclipse wiki here.

Error attaching to process: sun.jvm.hotspot.debugger.DebuggerException: Can’t attach to the process [ solved ]


I was in the process of getting the much awaited heap dump using jmap, from an ailing java process and booom !! This happens !!

Error attaching to process: sun.jvm.hotspot.debugger.DebuggerException: Can't attach to the process

Well, there are two things here that needs to be taken care off.

  1. The jmap process and the java process ( of whose, the heap dump is being taken ) should be running in the same user id.
  2. There is a linux ptrace bug which will prevent jmap from attaching to the java process. To resolve this, punch in the following command before you execute the jmap heapdump command.
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope

Now go ahead and execute the heapdump command using jmap.

jmap -heap:format=b <process-id>

and voila !!…You are done !! ūüôā ūüôā

 

JSON Jackson Example


JSON has been a popular data exchange format for some time now. What impresses me the most is it’s light weightedness and simplicity.Java has it’s fair share of JSON libraries which can be used for processing and creating JSON. Amongst all, Jackson beats the competion in popularity in the developer community.

Jackson is a multi-purpose Java library for processing JSON data format. Jackson aims to be the best possible combination of fast, correct, lightweight, and ergonomic for developers – From the Jackson Wiki

Here, i will demonstrate how to create JSON string from Java Object and vice versa. Without any further nonsense, lets get started with the example.

First let’s create the custom Employee object which we will use to generate the JSON Output. The Employee object comprises of an id(integer), name(String), department – represented by another custom class ‘Department’ and list of teammates(arraylist of Strings).

Department department = new Department(1, "IT");
List teamMates = new ArrayList() {
private static final long serialVersionUID = 1L;
{
add("karian");
add("jmm");
add("cp");
}
};
Employee employee = new Employee(101, "TJ", department, teamMates);

Now we will use the Jackson Library class ‘ObjectMapper’ to generate the JSON equivalent for the Employee Object constructed above.

ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(employee);

That’s it and this returns the following JSON output.

{"employeeId":101,"teamMates":["karian","jmm","cp"],"employeeName":"TJ","department":{"departmentId":1,"departmentName":"IT"}}

Let’s use the same generated JSON output to create the Employee object

String json = "";// Assign the above string here
ObjectMapper mapper = new ObjectMapper();
Employee employee = mapper.readValue(json, Employee.class);


The readValue() method accepts two parameters, the json input as String and the Class whose instance it should generate from the json input.

Wasn’t that easier than you thought ?

You can download the full code from this git repo : https://github.com/jollyarun/jackson-demo.git

Cheers !!
The Nonsense Blogger !!

JavaHL Issues with Eclipse Plugin


Issue with JavaHL library when using Eclipse

While using the subversion plugin ‘sublipse’ in Eclipse IDE, i ran into the following problem

Failed to load JavaHL Library.
These are the errors that were encountered:
no libsvnjavahl-1 in java.library.path
no svnjavahl-1 in java.library.path
no svnjavahl in java.library.path
java.library.path = /usr/lib/jvm/java-6-sun-1.6.0.03/jre/lib/i386/client::/
usr/lib/jvm/java-6-sun-1.6.0.03/jre/lib/i386::/usr/lib/firefox:/usr/lib/
firefox/:/usr/java/packages/lib/i386:/lib:/usr/lib

This is because the JavaHL library used by the SVN plugin in Eclipse to interface with SVN Server is missing or not available. There are two ways to rectify this.

  1. Install the JavaHL library and point eclipse to this.
  2. Use ‘PureSVNKit’ in SVN Preferenves in Eclipse ( Window -> Preferences -> Team -> ‘SVN Preferences’ )

I went for the first one. Here is how you do it

1. Install libsvn. In ubuntu, use the following command

sudo  apt-get install libsvn-java

2. This will install the file libsvnjavahl-1.so into the /usr/lib/jni directory. Standard installations of eclipse will automaticall pick it up. ( Only a restart of eclipse is necessary )

3. For non standard installations of eclipse, you wil need to edit the ‘eclipse.ini’ file in the eclipse home directory. To the ‘vmargs’ section of the file, add the following detail

-Djava.library.path=/usr/lib/jni

Find below, the contents of my eclipse.ini

-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
–launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.200.v20090520
-product
org.eclipse.epp.package.java.product
-showsplash
org.eclipse.platform
–launcher.XXMaxPermSize
1024m
-vm
/home/mindtree/java/jdk1.6.0_22/jre/bin
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Djava.library.path=/usr/lib/jni
-XX:MaxPermSize=1024m
-Xms40m
-Xmx512m
-vm
/home/mindtree/java/jdk1.6.0_22/jre/bin

What you are doing here is , we are passing the library location to the VM whcih runs Eclipse. So eclipse will look for ‘library files’ in this location as well.

For more on JavaHL, use the JavaHL FAQ @ http://subclipse.tigris.org/wiki/JavaHL

Back To Basics : Polymorphism in Java


What is Polymorphism

Polymorphism is the idea of invoking  different methods having the same name, but different implementations.

The following scenario explains it best. I have class called MyMathClass. Now, i need a method which will add two integers. This is what i do.

Class MyMathClass {

public int add(int a,int b) {

return (a+b);

}

}

Job well done. You create an instance of MyMathClass and use it to invoke the add¬† method which returns you the sum of two inetegers passed to it. That’s neat. ūüôā ūüôā

But what do you do if you want to expose a method which adds 3 integers or for that matter n¬† integers passed to it.¬†Imagine a situation where¬†there is no concept called polymorphism, you will have to create different implementations of the same add method with different names. Assume that you need to package and¬†expose this MyMathClass as an API. Now, the user’s of this API will need to¬†know the names of the different methods which performs the same functionality – add.¬†Now that does¬†not look very neat. ūüė¶ ūüė¶

This is where polymorphism makes its entry.  Polymorphism enables Class instances ( objects ) to refer to different method implementations having the same name. This is possible by varying the method signature ( the order or the number of parameters taken in as input by the method ). Find below, how MyMathClass gets transformed after polymorphism.

Class MyMathClass {

/* Method to add two integers */

public int add(int a,int b) {

return (a+b);

}

/* Method to add 3 integers */

public int add(int a,int b,int c) {

return (a+b+c);

}

/*Method to add n integers */

public int add(int a[],int n) {

int sum=0;

for(int i=0;i<n;i++){

sum = sum+a[i];

}

}

}

public MyMathClassDemo {

public static void main() {

MyMathClass myMathClassObject = new MyMathClass();

int sum = myMathClassObject.add(2,3); // Calls the add method for adding the two integers

sum = myMathClassObject.add(2,3,4); // Calls the add method for adding three integers

int a[] = new int[] {1,2,3,4,5};

sum = myMathClassObject.add(a,5); // Calls the method to add n integers

}

}

Now that’s polymorphism for you. Polymorphism itself is of two types – static and dynamic. The one explained above is static polymorphism.¬†ie the binding between the instance variable ( in this case, myMathClassObject ) and the method calls is done during the code compile time. Hence the name static polymorphism.

There is another type of polymorphism – dynamic polymorphism¬†where the binding is done during runtime or dynamically. But, that’s for a different post. Between, Hope this helps.

Cheers,

The Nonsense Blogger