Tag Archive for 'tips'

Java Tips: Iterate and cast

… (or More on cast away with Java generics)

Question: How many times did you encounter this kind of code?

List<Element> l = ...;
for (Element e : l) {
   if (e instanceof SubElement) {
      SubElement se = (SubElement) element;
      // do something
   }
}

If you get that so often, what do you think about this code?

List<Element> l = ...;
for (SubElement se : filter(l)) {
   // do something
}

Nice, huh?

I came across this idea after reading an article Cast away with Java generics. The article suggests a nice approach to cast.

    @SuppressWarnings("unchecked") public static <X> X cast(Object o) {
        return (X) o;
    }

And then you can use it to change an ugly code of:

Session webappSession;
        Map<String, Map<String, Collection<Entity>>> myUglyMap = (Map<String, Map<String, Collection<Entity>>>) (webappSession
                .getAttribute("myUglyMap"));

to a slightly better code:

Session webappSession;
        Map<String, Map<String, Collection<Entity>>> beautiful = cast(webappSession.getAttribute("beautiful"));

To get the nice iteration like I presented in the beginning of the article, I created two methods that reuse this cast method. Here they are:

   public static <X, T extends X> Iterable<T> filter(final Iterable<X> iterable) {
        return new Iterable<T>() {
            @Override public Iterator<T> iterator() {
                return new Iterator<T>() {

                    private T t = null;

                    @Override public boolean hasNext() {
                        while (iterable.iterator().hasNext()) {
                            try {
                                t = cast(iterable.iterator().next());
                                return true;
                            } catch (ClassCastException e) {}
                        }

                        return false;
                    }

                    @Override public T next() {
                        if (t == null) {
                            while (iterable.iterator().hasNext()) {
                                try {
                                    return cast(iterable.iterator().next());
                                } catch (ClassCastException e) {}
                            }
                        }

                        return t;
                    }

                    @Override public void remove() {
                        iterable.iterator().remove();
                    }
                };
            }
        };
    }

    public static <X, T extends X> Iterable<T> filter(final X[] iterable) {
        return new Iterable<T>() {

            @Override public Iterator<T> iterator() {
                return new Iterator<T>() {

                    private int index = 0;

                    @Override public boolean hasNext() {
                        while (index < iterable.length) {
                            try {
                                @SuppressWarnings("unused")
                                T element = cast(iterable[index]);
                                return true;
                            } catch (ClassCastException e) {}
                            index++;
                        }
                        return false;
                    }

                    @Override public T next() {
                        while (index < iterable.length) {
                            try {
                                return cast(iterable[index++]);
                            } catch (ClassCastException e) {}
                            index++;
                        }
                        return null;
                    }

                    @Override public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };

            }

        };
    }

The down side is of course you may have problem with performance because of ClassCastException. But I haven’t profiled it… yet.

Eclipse Tips: Template for iterating ResultSet

Those who works with Eclipse and JDBC can take a gross benefit from this little template.

Simply add the template. I use as name: ‘while’, context: ‘Java statement’, description: ‘iterate ResultSet’. You can certainly change them.

while (${en:var(java.sql.ResultSet)}.next()) {
	${cursor}
}

Play High Definition movie smoothly with VLC

VLC is a wonderful player. It can almost play all kind of videos that I have. It’s lightweight and best of all… it’s free! I don’t know what else to ask.

Except this… for several months I have noticed that when I played a high definition movie, it kind of getting chobby. It seemed that I have a line in the video. It made my eyes sick and I almost always try to avoid a HD movie (and hoping the problem will be fixed with the next version of VLC or Mac OS).

Today I got my Snow Leopard and VLC has left its beta status but I still get the horizontal line when I watch an HD movie. This is an example of it.

nothing

I thought… this is it. Either I manage to fix the problem in VLC or I have to find a new video player.

It turned out finding a better video player was a harder task.

So I began searching the web for a fix of that problem. It’s not that hard to find a solution, but to get the correct keywords is the harder puzzle. So in VLC forum, people suggested to use the filtering capability in VLC. At least there are three suggestions.

  1. To turn on the scale filter and use a better algorithm for it.
  2. To turn on the post processing filter and maximize the number of the post processing.
  3. To turn on the deinterlace filter.

I tried all of them to get the best solution, and after a while, I got a conclusion that turning on the deinterlace filter is the best answer. This was the result of it:
deinterlace

As you can see, the horizontal line is gone, but the picture is still not that sharp.

Not so satisfied with the result, I searched further for better solution. This time I got a better answer quicker. By using an algorithm named ‘Bob’ for deinterlacing, I got a better result as can be seen in the following picture.
bob

Now I’m glad!

Step by step instructions

If you are a type of person who needs a complete step-by-step instructions, this is what I did:

  1. Open VLC
  2. Select Preferences from the Menu ‘VLC’
  3. Activate the ‘All’ check box in the left bottom of the dialog
  4. Go to Video->Filters, activate the checkbox ‘Deinterlacing video filter’
  5. Go to Video->Filters->Deinterlace
  6. Change the deinterlace mode to ‘Bob’
  7. Click save
  8. Restart the VLC
  9. Play the video, hopefully you will get a better video playback

Do you have more tips how to optimize the settings in VLC? Please share here! I’d be glad to have a better and sharper image for my video.

Eclipse Tips: Debugging your multi thread application (2)

This post is another tips of debugging your multi thread application. If you are interested on how to debugging a multi thread application, probably you will find my first post useful as well.

In a multi thread application, it’s still possible to use a certain class from different threads. The problem is if you try to set a breakpoint in this shared class, the breakpoint will be valid for all threads. This is typically just slowing our debugging session.

With Eclipse, you can set a breakpoint that only valid in certain threads. The catch is since there is no way that Eclipse knows what threads will be available, you can only set this on runtime.

To do this, you need to first set the breakpoint you want (remember, you probably need to Suspend the VM as well).

After that, you can start the debugging session and wait until the application is suspended. In this occasion, let open the breakpoint properties. In this window, there are two elements in the left tree: Breakpoint Properties and Filtering. Select Filtering and after that you can set to which thread the breakpoint should be valid for.

2009-08-26_1300

There are two more catches.

  • If the intended thread is not running yet, this method is not usable.
  • Every time the debugging session is restarted, you’ll need to filter it again.

Despite that catches, I think this is nice feature to know by multi-thread application developers and who know, it may be useful sometime in the future.

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!