difference between hashmap and hashtable

Possible Duplicate:
Differences between HashMap and Hashtable?

I went to an interview the other day interviewer asked me under which situation will there be a problem to use hashmap rather then hashtable? Meaning give a eg where hashtmap use will result in problem but using hashtable will resolve the problem.

He told me that the machine in which the code is run is single core!!

I gave a eg

Time        Thread1            Thread 2
   t0    tb.put("a",1)       
   t1     tb.put("a",2)          int a = tb.get("a"); 

I told that if at t1 if both t1 and t2 executes simultaniously then it will result in problem. He said that since it is a single core cpu it will never execute 2 statements in parallel

Can someone please clarify that , when will there be a problem? Any example of situation?

EDIT:I posted the question by interchaing hashmap and hashtable.I know that hashtable method are synchronized and that of hashmap are not and i had told it to him

To experient i implemted following.And the code never crashed? I dint use hashtable but still it t is a hashmap in A :)

public class MyT extends Thread {

    HashMap<String,String > a = A.t;
    @Override
    public void run() {
        while (true) {
            a.put("a", "one");
            System.out.println(Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
        MyT t1 = new MyT();
        t1.start();
        MyT t2 = new MyT();
        t2.start();
    }
}

I think you have to do the following things first before asking:

  • Search on stackoverflow
  • Search on Google
  • The following results are obtained by above two methods:

    StackOverflow: Differences between HashMap and Hashtable?

    Google

    what is the difference between HashMap and Hashtable

    Difference between HashMap and HashTable? Can we make hashmap synchronized?

    Hope that helps :)


    Unlike the new collection implementations, Hashtable is synchronized. That's why I could imagine a situation when using Hashmap would create a problem, and using Hashtable would resolve it.

    The fact that it's single core is of no consequence: if Thread1 is pre-empted in the middle of a put call, Thread2 will see an inconsistent state, and may crash.


    Well, just because it's single core, doesn't mean you can't have race conditions. It possibly (probably?) means you won't have memory visibility issues, but you can certainly run multiple threads on a single core, and they can still be scheduled such that you get race conditions.

    链接地址: http://www.djcxy.com/p/16350.html

    上一篇: Java哈希表或哈希表?

    下一篇: 散列表和散列表之间的区别