Pages

Thursday, January 19, 2012

Synchronized vs ThreadLocal SimpleDateFormat

EDIT: This benchmark is not really reliable, as any other benchmark that is done just for fun - but here is the new one that pretends to have more sense.
It is widely known that SimpleDateFormat on the Java platform is not thread-safe. There are basically three approaches to deal with this unsafety. First - each time create new instance. Should be not very good, since it is not very simple and lightweight object. Synchronizing - I think should be better. And the third approach, that is used mostly in real world, I think - using ThreadLocal. I decided to test all these approaches. The result of my test is on the graph:
On the vertical axis here is the time, so the less - the better. On the horizontal axis is number of threads concurrently formatting dates. So what can be concluded from this graph?

  • Either SimpleDateFormat is not so heavyweight object, either synchronization is so heavy operation (I incline to the second option), but there is very little difference in synchronizing on one and the same instance of creating new one each time it is needed. However synchronizing is a bit better.
  • Widely used approach among the naive is the best.
EDIT: Doing this test I used Java6 from Sun. I have retested it with Java7 from Oracle and get quite different picture. The hardware is different too, so these pictures can not be compared with each other in absolute numbers. But difference in the relations between "new instance each invocation" approach and one synchronized instance is very interesting:

Anyway, here is the code I used for testing:

Monday, January 16, 2012

Oracle 11g denormalizing hierarchy with recursive subquery factoring and LISTAGG function

In Oracle 11g there are many new features. From the developer's point of view there are a bit less such features, but still there are some very impressive. Among these features there are recursive subquery factoring and LISTAGG grouping function. Here is how they can be combined together: