I have multiple threads of the same kind that are sharing the ArrayList:
static ArrayList<Integer> Terminate_List = new ArrayList<Integer>();
This ArrayList needs to be updated. I need to delete a single item of that list. The problem is when I reach the line
Terminate_List.remove(k);
The other thread already deleted another Item of the list, the size has decremented and I get a IndexOutOfBoundsException. So my plan was to make this method synchronized so that only one thread at a time can execute this method. The method is executed by a timer. How can I really let only one thread at a time execute this method?
public synchronized void update_list(){
for (int k = 0; k < Terminate_List.size(); k++) {
if (Terminate_List.get(k) == this_ID){
Terminate_List.remove(k); }}}
update_list()is.update_list()is in. Without seeing more code it's impossible to tell for sure.List, you haveCopyOnWriteArrayList. But IMO it would be better using another approach for your problem like aConcurrentHashMapinstead.