Sunday, December 24, 2017

java Synchronized ArrayList editing in multiple threads

java Synchronized ArrayList editing in multiple threads




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); }}}

dont utilize remove index - utilize remove reference. way dont 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 youre 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 - im assuming this_id defined int - if its integer dont need cast (and youd have problem equality check in original code).

java multithreading arraylist

go to link download
download
alternative link download

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.