Reading ArrayList in Concurrent system - java

I have a simple ArrayList and I am feeding this ArrayList from multiple Threads via Java concurrency. Each Thread will only read the same instance of this ArrayList. Is there any chance of error during the reading operation?

Provided there are no more writes make it immutable using Collections.unmodifiableList and then forget about read issues.

If the list is fully populated and always accessed in read-only by all the threads, you won't have a problem. If there is a write operation, then you need to synchronize all the accesses to the list, or to use a concurrent list (like CopyOnWriteArrayList).

Related

Java concurrent modification across threads

I have multiple threads constantly iterating through an ArrayList called "clients".
When they disconnect I want to remove a single client from the list but I am aware that it could cause a concurrent modification exception.
Should I surround all usage of the ArrayList with the Synchronized block or is that not a good idea?
Also can the ArrayList be read by multiple threads without a problem?
Thanks,
(The client list is constantly iterated by the UDP thread that sends data to all the clients)
I might not have a full information, but it seems that you always read and only sometimes write (change) to the array list. In this case, probably you should consider using:
Copy On Write Array List implementation
It should be better than using a regular synchronization because you don't want to get synchronized on read operations.
Here is an article that explains more pro- and -contra of using CopyOnWriteArrayList solution.

syncrhonize access on arrayList

i have a function which inserts inside an arrayList strings passed as parameter.This function can be accessed by different threads,
public void adding(String newStringForEachInvocation){
arrayList.add(newStringForEachInvocation);
}
i want to keep the add method concurrently and my doubt is, if two threads have got two differents strings is it possible for them to compete for the same bucket?
Another alternative is using the blockingQueue , but anyway it could represent a mutual esclusion for threads competing for the same bucket or not?
Yes, ArrayList is not thread-safe, and all the accesses to the list must thus be synchronized if it's accessed by multiple threads (explicitely, and/or by wrapping it using a Collections.synchronizedList()). Anything could happen if you're not doing it (data corruption, exceptions, etc.).
There are alternative, non-blocking List implementations, like CopyOnWriteArrayList. But depending on the use case it could be faster or slower than using a synchronized list.
Use Collections.synchronizedList, all unitary operation on that list will be synchronized
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList(java.util.List)
Be careful though, if you are going to accomplish more than one operation on that list, like an iteration, use a synchronized block to ensure the integrity of the list, as specified on the javadoc :
It is imperative that the user manually synchronize on the returned list when iterating over it

Are simultaneous reads from an array thread-safe?

I have an array which contains integer values declared like this:
int data[] = new int[n];
Each value needs to be processed and I am splitting the work into pieces so that it can be processed by separate threads. The array will not be modified during processing.
Can all the processing threads read separate parts of the array concurrently? Or do I have to use a lock?
In other words: is this work order thread-safe?
Array is created and filled
Threads are created and started
Thread 0 reads data[0..3]
Thread 1 reads data[4..7]
Thread 2 reads data[8..n]
Reading contents of an array (or any other collection, fields of an object, etc.) by multiple threads is thread-safe provided that the data is not modified in the meantime.
If you fill the array with data to process and pass it to different threads for reading, then the data will be properly read and no data race will be possible.
Note that this will only work if you create the threads after you have filled the array. If you pass the array for processing to some already existing threads without synchronization, the contents of the array may not be read correctly. In such case the method in which the thread obtains the reference to the array should be synchronized, because a synchronized block forces memory update between threads.
On a side note: using an immutable collection may be a good idea. That way you ensure no modification is even possible. I would sugges using such wrapper. Check the java.util.concurrent.atomic package, there should be something you can use.
As long as the threads don't modify the contents in the array, it is fine to read the array from multiple threads.
If you ensure all the threads are just reading, its thread safe. Though you should not be relying on that fact alone and try to make your array immutable via a wrapper.
Sure, if you just want to read it, pass the array to the threads when you create them. There won't be any problem as long as you don't modify it.
Reading from array array is Thread-Safe Operation but if you are Modifying array than consider using class AtomicIntegerArray.
Consider populating a ConcurrendLinkedQueue and have each thread pull from it. This would ensure that there are no concurrency issues.
Your threads would each be pulling their data from the top of the queue and processing it.

variable value changed simulateously by different threads

I have many concurrent running http request serving threads. They will be creating an Object(? extends Object) for every request and save the object in a list.
Advice me some good data structure to implement this list.
I can't use ArrayList since it was not thread safe.
I dont like to use Vector - since its synchronized, it will make other threads to wait when one of the http thread was saving the object.
Also tried LinkedList, but there is data loss due to concurrent update.
Your variable would need to be atomic so that it can safely be updated by multiple threads (see java.util.concurrent.atomic). You could also use an AtomicInteger to keep track of the number of times the variable is updated.
But are you sure you want do this without explicitly controlling the update to a variable?

synchronize versus Collection.synchronizedList versus CopyOnWriteArrayList

If my requirements dictate that most of my accesses to the list are for reading and modifications if any are going to be minimal, why can't I just do either of the following
synchronize modifyList method and use ArrayList. All reads from arraylist will be unsynchronized
or
inside modifyList, do a Collections.synchronizedList(arrayList)
or
CopyOnWriteArrayList (not sure what it buys here)
Why would I use either ? which is better ?
For 1 & 2, I'm not sure what you're trying to accomplish by only synchronizing writes. If there are potential readers who might be iterating the list, or who are looking things up by index, then only synchronizing writes proves nothing. The readers will still be able to read while writes are in progress and may see dirty data or get exceptions (ConcurrentModification or IndexOutOfBounds.)
You would need to synchronize both your reads and writes if you want 'safe' iterating and getting while other threads make changes. At which point, you may as well have just used a Vector.
CopyOnWriteArrayList is purpose built for what you want to do. It buys safe synchronization-free iterators, while substantially increasing the cost of writes. It also had the advantage of doing what you want (or what it seems you want from the terse question :) ), entirely encapsulated within the JavaSE API, which reduces 'surprise' for future developers.
(do note that if you have multi-step processes involving reads with 'get' even using CopyOnWriteArrayList may not be entirely safe. You need to evaluate what your code actually does and if an interleaving modification would break the method that is getting.)
Another solution would be to use ReentrantReadWriteLock so you can use read-only locks on read operations (which don't block other reads) and a write lock for when you're writing (which will block until there are no reads, and won't allow any read locks until it's released.

Categories

Resources