Tag Archive for 'java'

Page 2 of 2

Eclipse Tips: Auto generate ‘final’ on your variable, field, and parameter

If you are reading a lot of blogs about Java lately, you’ll find more and more people suggesting to use ‘final’ everywhere. The main argument is by using ‘final’ we will have a code with less bug. This post will not argue with the up/down side of the suggestion, if you eager to do that, just do that somewhere else (here for example).

However, if you are convince with such argumentation, probably the first thing on your mind is: should I now change all my code? How much time do I need to develop this instinct until all of my code is using ‘final’ everywhere?

Fortunately for Eclipse user, there is a functionality in Eclipse to help we develop this instinct. And it even will fixes our mistakes and we will get a consistent look of our code.

Let’s look at a code example:

2009-08-13_1139

There are some places where ‘final’ could be used. Now… open the Preferences dialog (under Window on Windows and Linux, under Eclipse on Mac). Navigate to Java->Editor->Save Actions.

2009-08-13_1142

Tick the ‘Perform the selected actions on save’ checkbox and ‘Additional actions’ checkbox. After that, click the ‘Configure…’ button.
2009-08-13_1146

What we’re interested in is in tab ‘Code Style’. Tick all ‘Private fields’, ‘Parameters field’, and ‘Local variables’. Click ‘OK’

Now you can go back to your source code and do small change, revert it back (Eclipse prevents saving if there is no change in the source code), and save it. Tarammm…. you get ‘final’ everywhere.

2009-08-13_1151

Note that this doesn’t put final on your method and class, you still have to do that manually.

Now you can enforce your team to use ‘final’ everywhere if you like!

Lambda4JDT: lambda expression on your Java code

This is just another proof how many people are starting to want some functional syntaxes on Java. Some lambda expressions are possible to be implemented using current Java, but there are just too many noise in the result.

Lambda4JDT provides a new plugin for Eclipse that can collapse the noise in the implementation without changing the syntax of Java. I must say that the approach it takes is pretty unique and original.


Java Tips: Optimizing your Map loop

Quite often, a program needs to go through all elements of a Map. Unfortunately, like a Set, a Map doesn’t have index in the data structure so you can’t just get a key of certain index or a value of certain index.

The most common practice used to iterate all elements in a Map is to get the key set and then based on the key, we can retrieve the value. The template we use for such case is something like this:

for (String k : m.keySet()) {
    Integer v = m.get(k);
   // do something with the key and value
}

This works of course, but based on quick observation, this should be not that efficient because we have to retrieve value using key for every step. It would be much better to get the key and value as a pair in the beginning. This is unfortunately less obvious and less used. The template would be something like this (of course, we need to change the generic type as properly):

for (Entry<String, Integer> e : m.entrySet()) {
    Integer v = e.getValue();
    // do something with the key and value
}

Now let’s make some tests. I use this template for the test and changing the backing object, number of iteration, and the method to get the key and value from the map (of course it’s not that real, because we only use the value and ignore the key, in which case we can use values() for better performance).

public static void main(String[] args) {
	java.util.Map<String, Integer> m = new TreeMap<String, Integer>();
	for (int i = 0; i < 500000; i++) {
		m.put(i + "", i);
	}

	List<Integer> l = new ArrayList<Integer>();

	long st = System.currentTimeMillis();

	for (String string : m.keySet()) {
		l.add(m.get(string));
	}

	System.out.println(System.currentTimeMillis() - st);
}

From my tests, I observe that the performance of the first template depends on the backing object. If we are using HashMap, the performance is less or more the same as the second template. If we are using Hashtable, the performance of the first template is about 1.5 times worse as the second template and if we are using TreeMap, the performance of the first template is more than 5 times worse as the second template. This proved my original hypotheses and we as developers should try to change our instinct to use the second template every time we encounter such problem.

UPDATE: I redo the test using nanotime and it’s just confirming my original observation.

Java Tips: Thread Safety Documentation

Joshua Bloch in his book, “Effective Java” summarized the levels of thread safety:

  • immutable—Instances of this class appear constant. No external synchronization is necessary. Examples include String, Long, and BigInteger (Item 15).
  • unconditionally thread-safe—Instances of this class are mutable, but the class has sufficient internal synchronization that its instances can be used concurrently without the need for any external synchronization. Examples include Random and ConcurrentHashMap.
  • conditionally thread-safe—Like unconditionally thread-safe, except that some methods require external synchronization for safe concurrent use. Examples include the collections returned by the Collections.synchronized wrappers, whose iterators require external synchronization.
  • not thread-safe—Instances of this class are mutable. To use them concurrently, clients must surround each method invocation (or invocation sequence) with external synchronization of the clients’ choosing. Examples include the general-purpose collection implementations, such as ArrayList and HashMap.
  • thread-hostile—This class is not safe for concurrent use even if all method invocations are surrounded by external synchronization. Thread hostility usually results from modifying static data without synchronization. No one writes a thread-hostile class on purpose; such classes result from the failure to consider concurrency. Luckily, there are very few thread-hostile classes or methods in the Java libraries. The System.runFinalizersOnExit method is thread-hostile and has been deprecated.

Let we find a simplest example of classes for each of the mentioned level.

Immutable

public class ImmutableClass {

    private String a;

    public ImmutableClass(String a) {
        this.a = a;
    }

    public String getA() {
        return a;
    }

}

Unconditionally Thread Safe

public class UnconditionallyThreadSafeClass {

    private String a;

    private Object syncObject = new Object();

    public UnconditionallyThreadSafeClass(String a) {
        this.a = a;
    }

    public void setA(String a) {
        synchronized (syncObject) {
            this.a = a;
        }
    }

    public String getA() {
        synchronized (syncObject) {
            return a;
        }
    }

}

Conditionally Thread Safe

import java.util.ArrayList;

public class ConditionallyThreadSafeClass {

    private ArrayList<String> a;

    private Object syncObject = new Object();

    public ConditionallyThreadSafeClass(ArrayList<String> a) {
        this.a = a;
    }

    public void add(String s) {
        synchronized (syncObject) {
            a.add(s);
        }
    }

    public ArrayList<String> getA() {
        return a;
    }

}

Not Thread Safe

public class NotThreadSafeClass {

    private String a;

    public NotThreadSafeClass(String a) {
        this.a = a;
    }

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }
}

Thread Hostile

public class ThreadHostileClass {

    private static String a;

    public ThreadHostileClass(String a) {
        ThreadHostileClass.a = a;
    }

    public String getA() {
        return a;
    }

    public void doSomethingToA(final String a) {
        new Thread() {
            public void run() {
                ThreadHostileClass.a = a;
            }
        }.run();
    }
}

Java Tips: Memory Optimization for String

String is a unique object in Java. The Java Specification explains several unique properties of String in Java. We might already know some of them. First, String is unique because it can be created without new keyword, like example below.

String s = "new String";

I have to mention that you can still create String object using new keyword, like this:

String s = new String("new String");

Does both statement “exactly equals”? Well, most of you also know that this is not true. The first example will try to reuse the same object whenever possible (and is correct because String is immutable) while the second will force the creation of new String object. Consider this example:

System.out.println("b" == "b");
System.out.println(new String("b") == new String("b"));

The result of first example is “true” while the second one will give “false”.

I almost certain that experienced programmer will never create String using new in normal use. But sometime, we are forced to use that. One case that I can think of is when you parse an XML file using SAX parser.

public class Reader extends DefaultHandler {

    private List<String> listString = new ArrayList<String>();

    public void characters(char[] ch, int start, int length) throws SAXException {

        String content = new String(ch, start, length);
        listString.add(content);

    }
}

This example works correctly but is not efficient. Once you have a document like this:

<test>
    <string>String</string>
    <string>String</string>
    <string>String</string>
    <string>String</string>
    <string>String</string>
    <string>String</string>
    <string>String</string>
    <string>String</string>
    <string>String</string>
    <string>String</string>
</test>

Try to profile your application, force garbage collection and you will still have ten String objects left in the memory.

Fortunately, Java has provided a method to avoid such case. You can use String.intern() to force the application to use the same String object whenever possible. For above example, you can change the code to something like this:

public class Reader extends DefaultHandler {

    private List<String> listString = new ArrayList<String>();

    public void characters(char[] ch, int start, int length) throws SAXException {

        String content = new String(ch, start, length).intern();
        listString.add(content);

    }
}

Now, re-profile the application, force garbage collection, and you will only have one String left in the memory. You can save a lot of memory if you can make sure that there is only one instance of String with certain value in your JVM.

This method also has nice side effect. If you do a lot of String equality comparison in the application, a same String object run faster. To explain this, we can read the source code of String:

...
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                    return false;
            }
            return true;
        }
    }
    return false;
}
...

If the object is same, then the method will be immediately after this line if (this == anObject). This is very fast and will save a lot of process time if your application do this operations a lot of time.

Java Tips: MessageFormat

Writing a working code is not enough. There is so wide spectrum from where we can distinguish good programmer and a bad one. This is one example of it.

Suppose we need to write a String that concatenate several predefined substrings with several variables. What do we do? Obviously, the most natural thing is to write:

String c = "The book with title " + title + " is sold with price "
              + price + " to " + buyername;

Nothing wrong with the code but obviously if the sentence build many times, you already know that it’s not that efficient. The use of StringBuffer or StringBuilder in Java 5 can make it much better.

String c = new StringBuilder("The book with title ").append(title)
                    .append(" is sold with price ").append(price)
                    .append(" to ").append(buyername);

Great! But not for future development. The code looks cryptic and hard to be changed. The use of MessageFormat is the best solution for such problem (which unfortunately, also the most inefficient).

String result = MessageFormat.format(
     "The book with title {0} is sold with price {1} to {2}",
      new Object[] {title, price, buyername});

This is even better since we can customize the format of the price, for example:

String result = MessageFormat.format(
     "The book with title {0} is sold with price {1,number,currency} to {2}",
      new Object[] {title, price, buyername});