Saturday, November 19, 2005

Some nice Java puzzles

I came across these set of interesting java puzzles and for many of them I got trapped. See how do you fare ;) If you have a good explanation, don't hesitate to share it.

  1. public class StringTest
    public static void main(String[] args){
    public static void foo(){
    String s = "str4";
    String s1 = "str" + s.length();
    System.out.println("(s==s1) = " + (s1==s));
    public static void bar(){
    String s = "str4";
    String s1 = "str" + "4";
    System.out.println("(s==s1) = " + (s1==s));

  2. public class Assignment {
    public static void main(String[] a){
    int count = 0;
    for (int i = 0; i < 3; i++)
    count += count++;

  3. class StaticTest {
    static { initIfNecessary(); }

    private static int sum;

    public static int getSum() {
    return sum;

    private static boolean initialized = false;

    private static synchronized void initIfNecessary() {
    if (!initialized) {
    for (int i = 0; i < 100; i++)
    sum += i;
    initialized = true;
    public static void main(String[] args) {

  4. package click;
    public class CodeTalk {
    public void doIt() { printMessage(); }
    void printMessage() { System.out.println("Click"); }
    package hack;
    import click.CodeTalk;
    public class TypeIt {
    private static class ClickIt extends CodeTalk {
    void printMessage() { System.out.println("Hack"); }
    public static void main(String[] args) {
    new ClickIt().doIt();

  5. public class Lazy {
    private static boolean initialized = false;
    static {
    Thread t = new Thread(new Runnable() {
    public void run() {
    initialized = true;
    t. start();
    try {
    } catch (InterruptedException e) {
    throw e.printStackTrace();

    public static void main(String[] args) {

Monday, November 14, 2005

Timestamp bugs..

I hit upon two JDK 1.5 bugs today both related to Timestamp.

  1. Till JDK 1.4.x, Timestamp.compareTo(Date) worked. With JDK1.5, it results into ClasscastException. Since Timestamp extends Date, the caller can always call date1.compareTo(date2) where date1 and date2 can be date or any of its subclass. Now with JDK1.5, if date1 is Timestamp and date2 is Date, it will result into ClassCastException. The code should have always been backward compatible. Try the code below

    Date date1 = new Date ();
    Date date2 = new Timestamp(System.currentTimeMillis());
    int result = date2.compareTo(date1);

  2. In some special cases, two different dates differing only in millisecond values are treated to be equal. You don't believe it?
    Lets take the code sample below, where you create date1 using the value only till second, and compare that with a timestamp date2 that was created with the entire value. Since date1 does not contain millisecond part, timestamp should be greater than date here but date.compareTo() treats them equal.

    long millis = System.currentTimeMillis();
    Date date1 = new Date(millis/1000*1000);
    Timestamp date2 = new Timestamp(millis);
    int i = date1.compareTo(date2);

    This used to work till JDK1.4. It got broken in JDK 1.5 because date now uses getMillis() to compare the time instead of comparing getTime() values. This change must have been made with good intention as getMillis() didn't need any computation and they would have thought that it will become faster. However Timestamp played spilsport here. When you create Timestamp object passing long millisecond value, it breaks it up in two parts - 'millis' in which it stores values till second and 'nanos' in which it stores everything after second. The Timestamp constructior looks like

    public Timestamp(long time) {
    nanos = (int)((time%1000) * 1000000);
    if (nanos < 0) {
    nanos = 1000000000 + nanos;

    Thus the millis value in this object will be only till second. hence the comparison of the two dates above will make them equal.

The lesson is that don't use compareTo() with dates. Write your own comparator for it in which you compare using date.getTime() :)

Saturday, March 19, 2005

serializable isolation level

Last 3 days have been playing around with DB isolation level trying to solve one customer issue. And this has confused me even more than I was till 3 days ago regarding this.

I always had the impression that serializable isolation level meant that DB will serialize all queries i.e if one query is being processed which involves certain rows and another query also comes for execution involving a subset of those rows, then DB will block this query and execute it only after 1st one is finished (committed or rolled back). But the result was no where close to what I was expecting.

Here is what happened when I tried with SQL server and Oracle server

Microsoft SQL Server

ssn1>select * from mytable where id=1;
no rows selected
ssn2>select * from mytable where id=2;
no rows selected
ssn1>insert into mytable values(1, 'name1');
ssn2>insert into mytable values(2, 'name2');
[dead lock..]

At this point "ssn2" gets deadlocked and then its deadlock mechanism detects it and rolls back the changes done by ssn2 and allows ssn1 to proceed.

I simply dont understand why is "ssn1" waiting while trying to insert. This behaviour simply means that DB client should take care of serializing the query and its not actually DB who is serializes.

Here is what Oracle DB does

ssn1>select * from mytable where id=1;
no rows selected

ssn2>select * from mytable where id=2;
no rows selected

ssn1>insert into mytable values(1, 'name1');
1 row inserted

ssn2>insert into mytable values(2, 'name2');
ORA-08177: can't serialize access for this transaction

So for oracle too, I need to serialize the queries myself?
The important thing is that both the sessions are trying to insert different rows and even then they can't do it.

Can someone explain to me when is this isolation level used, if they are used at all ;-) because in concurrent scenarios cases like above will happen very frequently and they are bound to fail.

I am not a DB guy and I might have overlooked some scenarios where 'serializable' is usable. But at this point of time this behaviour surely looks absurd to me.

Saturday, February 26, 2005

Do You Google ??

Well.. All of us would say ofcourse !!! several times a day.. but most of us do not use its power. forget about using, most of us are not even aware of it. At least I was not until a few days back :-)

1. You can search for all the related words by using keyword search i.e by prefixing the word with ~. So searching for '~travel' will return the results for travel, vacation, hotel etc.

2. Google ignores some common words like I, who, what, how etc. If you want that they must be included in the search, you must prefix that with '+'.

3. Similarly if you want to exclude some word from the search, you should prefix that with '-'.

4. normally google searches for the web pages but if you want it to search only for a particular file type, you can search using 'filetype:[type]'. For example if you want to search 'EJB Specification' and only pdf, then search for "EJB Specification filetype:pdf"

5. ofcourse we know how to search something in a particular site. thanks to google toolbar.. You can also do that using 'site:[domain]' or site:[home url]

So if you want to search something in all the 'edu' site you can search using e.g 'SHA-1 broken'

Similarly, if you want to search something on java Sun website, you can use ''

6. What if you want only those results where the word appears in the title. or those where the word appears only in links.. you can do these
allintitle:[word1][word2]... here results will have all the words in the title

7. Do you want to know which all pages link up to your website? very simple .. google up "link:[ur website]"
This will show all the pages who have links to your website

8. In the search box, when you type something what if it suggests you what you are looking for.. Just like code-completion in IDEs.
Cool.. ehh!!!
try this out.

9. You found a page which you found interesting. And you want to search other similar sites. Google up "related:[site]" e.g ""

10. You wanted to search some thing and you were not able to locate anything. Now you have some one at your service (courtesy google) who will do
all the research for you (ofcourse for some price ;-)) and give you the answer you wanted.
check out

Happy Googling..

Tuesday, February 01, 2005

weekend in NewYork

I am here in newton (near Boston) for the induction programme of Macromedia and having good time :-)
Spent the last weekend in NY city with khandi, gurdeep and aman. Undoubtedly NY is the best city in the world. You just feel that you are in a completely different world. (and for a change I had not seen so many people together in US).
Some pics here.. See more of it here


Thanks to Ramesh, Rajiv and Sachin for introducing me to the blogging world... but i was too lazy to create one for myself.. and ofcourse was busy reading thier blogs ;-) Finally after months of laziness I created one :-) Hope i don't get too lazy this time. hehehe