multithreading - Multithreaded code in Java with ExecutorService fails to return, why? -
i have similar multithreaded code elsewhere in codebase works fine, can't see quite what's going wrong here.
this simple multi-threaded process generate result xml search query. output of running method is:
returning threads
the line system.out.println("finished multithreading loop");" never reached.
modifying number of threads doesn't help.
private void fillallresults() { int threads = 2; final futuretask[] tasks = new futuretask[threads]; final executorservice executor = executors.newcachedthreadpool(); (int = 0; < allresults.size(); i++) { tasks[i] = new futuretask<integer>(new callable<integer>() { public integer call() throws exception { int index; while ((index = getresultsindex()) < allresults.size()) { system.out.println("processing result " + index); result result = allresults.get(index); fillresultxml(result); } system.out.println("returning threads"); return 1; } }); executor.execute(tasks[i]); } (int = 0; < threads; i++) { try { tasks[i].get(); } catch (interruptedexception e) { e.printstacktrace(); } catch (executionexception e) { e.printstacktrace(); } } executor.shutdown(); system.out.println("finished multithreading loop"); }
edit, quick replies! here's answers:
it shows 'processing result' many times have results. if allresults.size() 25, shows processing result 1, processing result 2 ... processing result 24.
here's code that's missing:
private list<result> allresults = new arraylist<result>(); private int resultsindex = 0; private synchronized int getresultsindex() { return resultsindex++; }
and in case anyone's wondering, can guarantee none of code within loop increases size of allresults.
i suppose related fact, array tasks
has length of threads
(i.e. 2 in case) assign more values within lines
for (int = 0; < allresults.size(); i++) { tasks[i] = ... .... }
if list allresults
has more 2 entries thread stopped arrayindexoutofboundsexception
. maybe catch 1 not handle outside code presented.
Comments
Post a Comment