javamultithreadingconcurrencyperformancelocking

Java Concurrency: lock efficiency


My program has 100 threads.

Every single thread does this:

1) if arrayList is empty, add element with certain properties to it

2) if arrayList is not empty, iterate through elements found in arrayList, if found suitable element (matching certain properties), get it and remove the arrayList

The problem here is that while one thread is iterating through the arrayList, other 99 threads are waiting for the lock on arrayList.

What would you suggest to me if I want all 100 threads to work in lock-less condition? So they all have work to do?

Thanks


Solution

  • Have you looked at shared vs exclusive locking? You could use a shared lock on the list, and then have a 'deleted' property on the list elements. The predicate you use to check the list elements would need to make sure the element is not marked 'deleted' in addition to whatever other queries you have - also due to potential read-write conflicts, you would need to lock on each element as you traverse. Then periodically get an exclusive lock on the list to perform the deletes for real.

    The read lock allows for a lot of concurrency on the list. The exclusive locks on each element of the list are not as nice, but you need to force the memory model to update your 'deleted' flag to each thread, so there's no way around that.