java - NoSuchElementException even after check -
for (final arraylist<smartphone> smartphones : smartphonescluster) { new thread(new runnable() { @override public void run() { (smartphone smartphone : smartphones) { queue<smartphonetask> tasks = smartphone.getsystem() .gettaskque(); smartphonetask task = null; assert tasks != null; try { while (!tasks.isempty()) { task = tasks.poll(); // line throwing exception (globalnetwork.java:118) assert task != null; task.execute(); task.ontaskcomplete(); } } catch (runtimeexception e) { e.printstacktrace(); } } } }).start(); } and log:
java.util.nosuchelementexception @ java.util.linkedlist.remove(linkedlist.java:788) @ java.util.linkedlist.removefirst(linkedlist.java:134) @ java.util.linkedlist.poll(linkedlist.java:470) @ com.wtsang02.reu.botnet.network.globalnetwork$1.run(globalnetwork.java:118) @ java.lang.thread.run(thread.java:662) java.lang.nullpointerexception exception in thread "thread-299" java.lang.assertionerror @ com.wtsang02.reu.botnet.network.globalnetwork$1.run(globalnetwork.java:119) @ java.lang.thread.run(thread.java:662) line 118 points to:
task=tasks.poll(); how solve this? queue linkedlist implemenation if makes difference.
linkedlist not thread-safe, need external synchronization if access linkedlist on more 1 thread. synchronization on object (a synchronized method shorthand "synchronize on this"), , both gets , puts must synchronized on same object. you're doing here, since create new thread each smartphone, , access phone's linkedlist there.
if 1 thread puts list while synchronized on someobject1, , thread reads list while synchronized on someobject2, not count external synchronization -- code still broken.
even if used thread-safe collection, it'd possible hit exception if multiple threads emptying queue @ same time. instance, imagine this:
thread a: put e queue1 thread b: queue1.isempty()? no, go on thread c: queue1.isempty()? no, go on thread b: queue1.poll() // works thread c: queue1.poll() // nosuchelementexception you should use blockingqueue, poll() method return null if there no more elements in list. keep pulling until null, , break loop.
Comments
Post a Comment