java - Synchronized ArrayList editing in multiple threads -
i have multiple threads of same kind sharing arraylist:
static arraylist<integer> terminate_list = new arraylist<integer>();
this arraylist needs updated. need delete single item of list. problem when reach line
terminate_list.remove(k);
the other thread deleted item of list, size has decremented , indexoutofboundsexception. plan create method synchronized 1 thread @ time can execute method. method executed timer. how can allow 1 thread @ time execute method?
public synchronized void update_list(){ (int k = 0; k < terminate_list.size(); k++) { if (terminate_list.get(k) == this_id){ terminate_list.remove(k); }}}
don't utilize remove
index - utilize remove
reference. way don't have worry indexes @ all.
also, terminate_list
static, while method not. means if have multiple instances of class, blocking occur 2 threads area accessing same instance. block other threads updating terminate_list
, need update how you're using synchronized.
your code become this:
public void update_list(){ // previous impl equivalent synchronized(this) synchronized (terminate_list) { terminate_list.remove((integer)this_id); } }
note - i'm assuming this_id
defined int
- if it's integer
don't need cast (and you'd have problem equality check in original code).
java multithreading arraylist
No comments:
Post a Comment