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?
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With