I'm not sure if this is the correct way to synchronize my ArrayList
.
I have an ArrayList
in_queue
which is passed in from the registerInQueue
function.
ArrayList<Record> in_queue = null;
public void registerInQueue(ArrayList in_queue)
{
this.in_queue = in_queue;
}
Now I'm trying to synchronize it. Is this sychronizing my in_queue
object correctly?
List<Record> in_queue_list = Collections.synchronizedList(in_queue);
synchronized (in_queue_list) {
while (in_queue_list.size() > 0) {
in_queue_list.remove(0);
}
}
Let's take a normal list (implemented by the ArrayList class) and make it synchronized. This is shown in the SynchronizedListExample class. We pass the Collections.synchronizedList method a new ArrayList of Strings. The method returns a synchronized List of Strings. //Here is SynchronizedArrayList class
Notice that when iterating over the list, this access is still done using a synchronized block that locks on the synchronizedList object. In general, iterating over a synchronized collection should be done in a synchronized block
That's correct, and documented:
http://java.sun.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List)
However, to clear the list, just call List.clear().
Looking at your example, I think ArrayBlockingQueue (or its siblings) may be of use. They look after the synchronisation for you, so threads can write to the queue or peek/take without additional synchronisation work on your part.
You're synchronizing twice, which is pointless and possibly slows down the code: changes while iterating over the list need a synchronnization over the entire operation, which you are doing with
synchronized (in_queue_list)
UsingCollections.synchronizedList()
is superfluous in that case (it creates a wrapper that synchronizes individual operations).However, since you are emptying the list completely, the iterated removal of the first element is the worst possible way to do it, sice for each element all following elements have to be copied, making this an O(n^2) operation - horribly slow for larger lists.
Instead, simply call
clear()
- no iteration needed.Edit: If you need the single-method synchronization of
Collections.synchronizedList()
later on, then this is the correct way:But in many cases, the single-method synchronization is insufficient (e.g. for all iteration, or when you get a value, do computations based on it, and replace it with the result). In that case, you have to use manual synchronization anyway, so
Collections.synchronizedList()
is just useless additional overhead.Yes it is the correct way, but the synchronised block is required if you want all the removals together to be safe - unless the queue is empty no removals allowed. My guess is that you just want safe queue and dequeue operations, so you can remove the synchronised block.
However, there are far advanced concurrent queues in Java such as ConcurrentLinkedQueue