Erik Bennett
Erik Bennett

Reputation: 1099

When is the wrong time to use a Collections.synchronizedList vs. a List?

Other than a (minor?) performance hit, why would I use a regular List instead of a Collections.synchronizedList vs. a List?

The project I'm working on is under 10k entries, so I don't care, but if someone (maybe me) chooses to sub-class this, I need to document the behavior.

Besides performance (over 100k entries), why would I not synchronize?

That is, what penalty do I incur for using a synchronizedList? How bad is it? For my current application, it's not an issue. If it is a cheap addition, why not?

Upvotes: 0

Views: 572

Answers (2)

Stephen C
Stephen C

Reputation: 718826

Other than a (minor?) performance hit ...

In fact, if the list is shared between threads, the performance hit of using a simple synchronized list (versus something more appropriate) could be a large performance hit, depending on what you are doing. The synchronized operations could become a concurrency bottleneck, reducing the application to the performance of a single core.

Simple "black and white" rules are not sufficient when designing a multi-threaded application ... or a reusable library that needs to be thread-safe and also performant in multi-threaded applications.


That is, what penalty do I incur for using a synchronizedList? How bad is it? For my current application, it's not an issue. If it is a cheap addition, why not?

The synchronized list class uses primitive object locking (mutexes).

  • If the lock is uncontended, this is cheap; maybe 5 or 10 instructions each time you acquire and release the lock. However, the ovehead may depends on whether there was previous contention on the lock. (Some locking schemes cause an object lock to be "inflated" the first time that contention occurs ...)

  • If the lock is contended, then it is more expensive because this will typically involve the blocked thread being de-scheduled and rescheduled ... and context switch overheads. There is another JVM-level implementation approach involving "spin locking", but that entails the blocked thread testing the lock object in a tight loop.

  • If the lock is held for a long time (e.g. in list.contains ... for a long list.) then that typically increases the probablility of contention.

Upvotes: 2

user207421
user207421

Reputation: 310909

When you don't need the synchronization, or when you aren't deluding yourself that a synchronized list is thread-safe even when iterating, which it isn't.

Upvotes: 1

Related Questions