Archive for the ‘Java’ Category

Parsing Strings to DateTime (or LocalDate) using Joda time

Friday, November 27th, 2009

There’s no doubt that Joda time is now the defacto date time library for java. And a well written library it is. You get almost everything you can ever want to do with Date objects and best of all, almost all operations are dummy-proof. By dummy proof I mean that programmers making silly mistakes can’t really screw it up.

I recently had to parse a String into a LocalDate object using Joda time. I couldn’t find a parser in the docs or the very useful userguide but I knew it had to be possible, no one could overlook such a widely used operation. So I went in search of a parse.

It turns out that the parser and the formatter are one and the same thing in joda time, except with different methods ofcourse. Here’s how you construct a parser to parse a String in YYYYMMDD format :

DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder().appendYear(4, 4).appendMonthOfYear(2)
            .appendDayOfMonth(2).toFormatter();

(more…)

Hibernate join tables for entity mapping – using them helps

Sunday, November 22nd, 2009

Over the last couple of years I have had various discussions about this with my colleagues. I myself favoured foreign keys relationships rather than join tables till a little while ago. If you’re not aware of how to do one or the other, the eamples below should explain that.

Consider a very simple parent child relationship. Every parent can have multiple children. Using a join table and JPA annotations, the model classes look something like this for unidirectional relationships: (I have excluded all fields not required for this example)
With join table …

@Entity
class Parent {
    @OneToMany
    @JoinTable(
            name="parents_children",
            joinColumns = @JoinColumn( name="parent_id"),
            inverseJoinColumns = @JoinColumn( name="child_id")
    )
    private Set<Child> children
}

@Entity
class Child {
    //nothing
}

Without join table …

@Entity
class Parent {
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinColumn(name="parent_id")
    private Set<Child> children;
}

@Entity
class Child {
    // nothing
}

(more…)

Difference between decorator and proxy patterns

Wednesday, November 18th, 2009

I had an interesting discussion with a colleague of mine regarding the differences between the proxy and the decorator pattern which made me give it some thought. To the untrained eye (that includes my eye!), they seem exactly the same. Infact you sometimes wonder, why the heck are there two names for the same pattern. As we’ll soon see, they are anything but the same.

I think we’re all aware that the decorator pattern is used to add behavior to existing code. This does not stop at one kind of behavior but any number of different things that we want to do. A proxy on the other hand simply delegates all calls to the underlying object delaying costly operations till they are absolutely neccessary. This basically means that what a proxy can do is decided at compile time and cannot be changed by the calling code after instantiation. Using the decorator pattern the behavior of the underlying object can be changed at runtime by adding multiple decorators to it. This behavior addition takes place at runtime depending on say user input. To put it simply, proxy is compile time, decorator is runtime.
(more…)

The usefulness of java.util.concurrent.TimeUnit

Wednesday, October 14th, 2009

I’m a bit ashamed to write this post. I have been working on Java 5 for well over two years and yet I was unaware of the power of the java.util.concurrent.TimeUnit class. While I have used almost all the other juc classes over this time and subsequently TimeUnit as well (in some of them), I never realized how powerful TimeUnit was on its own.

It all started with my obsession to remove all the checkstyle errors in a project that I have been working on. More than 50% of them turned out to be ‘magic number’ warnings. While some of them were my fault, most of them were due to laziness and then there were some due to Thread.sleep calls in the code. There must be an easy way to get rid of these without actually having to make private static final class members for every sleep value. I looked and looked and looked, nope, nothing.
(more…)

Small java changes which should be in Java 7

Wednesday, April 8th, 2009

It’s ironic the stuff we get used to as developers. There’s so much we do repeatedly in every class or in every project or maybe even in every method yet we never realize that it’s probably best to add a new “feature” to java to make our life easier. While searching for some reading material on java’s handling of String (just to clear up some of my own personal doubts) I came across a very interesting OpenJDK sub-project, Coin. Coin, simply put, is a project to determine what small language changes should be added to JDK7. Wonderful, let’s see what people have come up with. And that’s just week 4 submissions.
(more…)

Simple concurrent In-memory cache for web application using Future

Wednesday, March 11th, 2009

In-memory cache’s can be extremely useful for small web applications where you don’t want to full-blown cache system like ehCache or simply can’t afford one. I recently had such a requirement and I must say that I kind of made a mess of it. The requirement was to cache User objects so that we didn’t have to make too many calls to the database. Let me just say outright that while such a cache is not the best idea in the world, it isn’t the worst either. When you simply need to cache a few objects to reduce the load on the db in a moderately loaded web-app, this implementation works just fine.

The service layer was my choice for the cache, I use the Controller -> Service -> DAO model in all my webapps mainly because it keeps the code clean and also because it makes it much easier to manage transactions across DAO’s. (more…)

Method inlining with the final keyword in java

Thursday, February 12th, 2009

I have noticed a lot of people on the internet asking about method inlining. The term generally arises whenever the final keyword is discussed. Basically, it is said that compilers inline methods which are declared final thereby avoiding the cost of putting them on the stack etc and thus improving performance drastically under heavy load conditions. The same is true for variables as well, their values are inlined thereby avoiding the cost of performing lookups at runtime. What nobody talks about is what exactly is inlining.

Consider the following class :

public class Inline {

	private int	i;

	public void methodA() {
		methodB();
	}

	public final void methodB() {
		i++;
                i--;
	}
}

methodB() is marked final in this case. It cannot be overriden. The compiler sees this and decides to alter the byte code of methodA() to instead look like this :

public void methodA() {
		i++;
		i--;
	}

methodB() has now been inlined into methodA() to save the cost of pushing a method onto the stack. This invocation will work faster than the earlier one although its almost impossible to determine how much faster without a proper production environment. It’s also important to note that java code is first compiled into byte code and then into runtime code by the JVM. This change of code takes place in the JVM and not during compilation. If you open your class file you will see nothing different in it from the source file.

final variables work in the same way except calls to them are replaced by their actual values because those are not going to change once they’re initialized.

It’s been said that the newer VM’s (ever since Hotspot) no longer provide benefits of marking methods and variables final as they deduce and mark them final on their own during runtime.

Why ConcurrentHashMap is better than Hashtable and just as good as a HashMap

Thursday, February 5th, 2009

ConcurrentHashMap is a pretty ignored class. Not many people know about it and not many people care to use it. The class offers a very robust and fast (comparatively, we all know java concurrency isn’t the fastest) method of synchronizing a Map collection.

I have read a few comparisons of HashMap and ConcurrentHashMap on the web. Let me just say that they’re totally wrong. There is no way you can compare the two, one offers synchronized methods to access a map while the other offers no synchronization whatsoever. What most of us fail to notice is (more…)

Java job scheduling and cron

Saturday, January 31st, 2009

More often than not you need your java program to perform an operation at a particular time. It gets trickier when the operation needs to be performed at regular intervals. There are a lot of solutions to implement a java “cron” of sorts available. There’s the quartz scheduler which has pretty much everything that you will ever need in terms of scheduling, then there’s Spring TaskExecutor’s which can do pretty much everything but are a lot easier to configure than a full blown job scheduler.
(more…)

Difference/Comparison between/of Serializable and Externalizable

Friday, January 30th, 2009

I’m asked the difference between the two interfaces, Serializable and Externalizable more often than i’d like. It’s pretty simple really. Serializable does all the dirty work for you, it writes the object to the output stream on it’s own without you having to bother about anything at all. Externalizable on the hand makes you do ALL the work. You must handle the reading and writing on your own.

 

The easiest difference to remember is the methods to be implemented by the class. That information can be easily obtained from the javadocs.

The major difference however, the one most people miss, is that the default no-arg constructor is called during the reconstruction of an object who’s class implements the Serializable interface. However, this call is not made for a class which implements the Externalizable interface.

Hope that helps.

Generics in Java 5.0

Friday, October 12th, 2007

Of all the new topics in Java 5.0, the most confusing has been Generics, atleast for me. I realised that, while studying for SCJP 1.5, I would need a summary of generics so it doesn’t escape me a little while later.

(more…)

The world now belongs to Skype

Monday, May 22nd, 2006

Calling International from India has always been a … pain to say the least. First off, getting through was impossible. Notice how I say “was” because that was the case in the early and mid 90’s. With the entry of private operators into the field, things got easier because the state monopoly was over. Getting through to an international number is relatively easy today and simple. The only problem is mobile operators take about a week to activate your ISD (I have no idea why). (more…)

How Pool.com managed to get 60% of .eu domains on the first day

Sunday, April 9th, 2006

I stand corrected. I always though things like these were about 100 times more likely to happen in a third world country than in a “union”, european union more specifically. I’m talking about the recent .eu domain name fiasco. Simply put, Pool.com a registrar, cheated to obtain .eu domains on the first day of the sale. Anyone who’s aware of the internet knows what power a good domain name holds, examples of domain names being sold for thousands of dollars (and even millions sometimes) can be found everywhere. Pool.com is going to have a nice bundle of cash once they’re done auctioning off their domain names. Nadeem Azam has written a very good article describing the entire fiasco in detail. (more…)