Synchronize it?

Hi all,

okey here is the deal :P

class List

{

Hashtable data;

....

public void add(String key, String text)

{

data.put(key, text);

}

public void remove(String key)

{

data.remove(key);

}

}

Methods in hashtable are synchronized, so data will be locked if add is called in the List, but the List object it self will not be locked right? So if another thread calls remove it will not be blocked on List but on data (if another thread is busy with it), so that's still safe right?

If learned that an object can be seen as a plane with a bathroom. When threads (people who want access to the bathroom) want to access it, they check if it's locked, if it's locked they wait in line or else they go inside and lock it for themselfs.

so in this case data is the plane, but what happends if I also synchronize the methods in List. Will the then become an plane that bigger then the other plane with the smaller plane inside of it?

And what happends if I extend List with another class and do I have to Synchronize methods in that class as well and will this be a performace loss?

Thnx in advance

David

[1237 byte] By [DarkieDuck] at [2007-9-26 21:25:19]
# 1

The way you do it know is thread-safe. Two threads can call methods on the List class at the same time, but they will not be able to modify the Hashtable at the same time since it is thread safe.

There is no need to make the methods in List synchronized in this case, that would just mean you would have to require the lock for the List object, and then the data lock. It will affect the performance a little (but probably not noticable in this example), to have both List and Hashtable synchronized.

And you don't need to make subclasses of List synchronized either.

abnormal at 2007-7-3 21:13:48 > top of Java-index,Core,Core APIs...
# 2
THANK YOU VERY MUCH!!!
DarkieDuck at 2007-7-3 21:13:48 > top of Java-index,Core,Core APIs...