Which List should be used, to remove in a thread safe way?
Hello all,
I plan to have a List, where n number of Threads will accessing the List.
When two or more thread trying to remove an equals items from the List, only one of the thread will remove successfully (i,e, remove(Object o) will return true). The rest of the threads will realize remove(Object o) returns false
I wish to achieve this. I know that I can achieve by using :
Collections.synchronizedList(new ArrayList(...))
However, I afraid having the synchronized block will slow down my execution speed. Is there other way, that I achieve the same objective with faster speed? For example, using CopyOnWriteArrayList?
Thanks!
[705 byte] By [
KwangHooia] at [2007-11-27 7:06:59]

# 5
Sorry,
I said "badly" because it is synchornized by putting "synchronized" keyword on most of the methods prototypes.
Which equals to synchronizing on "this".
In my opinion, one problem of this implementation is that 2 calls to a get() method will be synchronized wherever they dont need to. (As get() does not modify the vector). [See Edit]
One other is you can synchronize on the Vector's mutex (itself) outside of the Vector's code.
And at last, as synchronizedList is not implemented by a Vector and is more recent than the Vector implementation...
I guess they implemented it in another way for many good reasons...
[Edit]
As i can see in Collections, the synchronizedList is implemented in the same way.
BUT, as the synchronized keyword is not in the method's prototype, we can expect the implementation to be changed a day...
And vector is a kind of old object kept for backward compatibility i guess. (someone can confirm ?). ("As of the Java 2 platform v1.2, this class has been retrofitted to implement List, so that it becomes a part of Java's collection framework.")
@KwangHooi
You can write your own implementation of a List which will not synchronize on the same token for both read/write operations. (but, i guess it could be hard to avoid deadlocks)
ibanna at 2007-7-12 18:58:18 >
