Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make your collections thread-safe?

When designing a collection class, is there any reason not to implement locking privately to make it thread safe? Or should I leave that responsibility up to the consumer of the collection?

like image 970
core Avatar asked Oct 02 '08 19:10

core


2 Answers

Making the collection threadsafe is what killed Java's Vector and Hashtable classes. It is far easier for a client to wrap it in a threadsafe wrapper, as previously suggested, or to synchronize data access on the subset of methods, than to take a synchronization hit every time the class is accessed. Hardly anyone uses Vector or Hashtable, and if they do, they get laughed at, because their replacements (ArrayList and HashMap) are worlds faster. Which is unfortunate, as I (coming from a C++ background) much prefer the "Vector" name (STL), but ArrayList is here to stay.

like image 153
MetroidFan2002 Avatar answered Oct 13 '22 00:10

MetroidFan2002


is there any reason not to implement locking privately to make it thread safe?

It depends. Is your goal to write a collection class which is accessed by multiple threads? If so, make it thread safe. If not, don't waste your time. This kind of thing is what people refer to when they talk about 'premature optimization'

Solve the problems that you have. Don't try to solve future problems that you think you may have some years in the future, because you can't see the future, and you'll invariably be wrong.

Note: You still need to write your code in a maintainable way, such that if you did need to come along and add locking to the collection, it wouldn't be terribly hard. My point is "don't implement features that you don't need and won't use"

like image 30
Orion Edwards Avatar answered Oct 13 '22 00:10

Orion Edwards