Jake
Jake

Reputation: 15217

Java: Better to get lock once or multiple times?

I realize this is a somewhat general question, but bear with me. Suppose that I have to insert a bunch of items into a data structure.

Do you think it would be better to insert in batches or one-by-one or it doesn't matter (...where "better" minimizes insertion time and lock hold time)?

Upvotes: 0

Views: 188

Answers (2)

Tudor
Tudor

Reputation: 62439

If only one thread has access to your data structure, then you don't need the lock at all.

If multiple threads need access then it's a matter of how large is the "dosage":

  • If you lock for each item, then you have very fine grain locking and multiple threads can probably update the list alternatively, allowing all of them to make progress. However, locking and unlocking many times will start to add up.
  • If you lock for the entire batch, then locking has negligible impact, but if the batch is large the other threads will be locked-out until you finish the entire update.
  • A trade-off would probably be to divide the large batch into a few smaller batches, such that you don't take the lock too many times, yet all the threads are allowed to make some progress by having a chance to take the lock between batch updates.

Upvotes: 2

using a lock, generally speaking, would be to preserve the atomicy of the operation. If the whole insertion is done from one thread and you want to ensure that all items are inserted while no other thread in the system can acquire the lock in he middle of the operation - you should choose the giant batch. This choice is also performance-wise if looking on the operation itself (only acquire the lock once). On the other hand, if other parts of the system might, while the thread is inserting in giant batch, want to insert or do any other operation that needs to get the lock, they will 'starve'. So it really a choice of usage by the whole system. If you find out that you are the only thread ever using the lock - you can actually dismiss it...

Hope it helps.

Upvotes: 0

Related Questions