Reputation: 10122
Can you synchronize an ArrayList like this:
ArrayList<Integer> myList = new ArrayList<Integer>();
synchronized (myList) {
// add, delete, and modify list here is okay
}
I cannot use synchronized ArrayList returned by Collections
utility class so is above code okay?
Upvotes: 0
Views: 125
Reputation: 10142
You can synchronize
on any Java Òbject
and ArrayList
too is an Òbject
, so its a valid syntax but since you have written in commented code that,
// add, delete, and modify list here is okay
I guess , functionally this not what you want to achieve. I think, you want to add, delete and modify to ArrayList
in a synchronized way when multiple threads try to access that piece of code.
If you do synchronized (myList)
, you are simply using list as a lock and nothing else i.e. this doesn't make operations on myList
thread safe.
Instead of that, you should do synchronized (this)
where this
is an instance of class containing sample code listed by you then within that block you perform operations on myList
like adding element, deleting element etc.
synchronized (myList)
is not functionally correct if you are looking for a replacement of Collections.synchronizedList
because each thread will hold a lock on new object since you are doing new ArrayList<Integer>()
for every new thread. You need to synchronize on same object for each thread.
Also, you don't need a synchronized access to list at all if myList
is not a field shared by multiple threads since you are creating a new ÀrrayList`every time so each caller thread works on a new list.
Upvotes: 1
Reputation: 12948
You don't need to implement with effort.
You can use a synchronizedList,
Ex:
List myList = Collections.synchronizedList(new ArrayList<Integer>());
Upvotes: 0