Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Concurrency: lock effiency

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

like image 944
Andrey Avatar asked Feb 05 '10 04:02

Andrey


People also ask

Are Java locks fair?

In a fair lock, threads acquire the lock in the order they request it. In a non-fair lock, jumping ahead is allowed. When requesting the same lock later, a later thread can get the lock before the waiting threads. The tryLock() method of the ReentrantLock class always uses a non-fair lock.

Why locks are better than synchronized?

Lock framework works like synchronized blocks except locks can be more sophisticated than Java's synchronized blocks. Locks allow more flexible structuring of synchronized code.

Is Java good for concurrency?

While Java isn't necessarily the best language for concurrency, there are a lot of tools, libraries, documentation and best practices out there to help. Using message passing and immutability instead of threads and shared state is considered the better approach to programming concurrent applications.

How do you avoid concurrency issues in Java?

The simplest way to avoid problems with concurrency is to share only immutable data between threads. Immutable data is data which cannot be changed. To make a class immutable define the class and all its fields as final. Also ensure that no reference to fields escape during construction.


1 Answers

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.

like image 74
TheDon Avatar answered Oct 02 '22 08:10

TheDon