java - FutureTask call() refer object, result wrong -
i want result
jsonobject={"key":[2,2,3]} jsonobject={"key":[2,4,3]} jsonobject={"key":[2,4,6]}
but result is
{"key":[2,4,6]} {"key":[2,4,6]} {"key":[2,4,6]}
i dont know what's wrong. please help. thanks!
how change code? object last number.
code is:
public class testfuturetask { public static void main(string[] args) { int[] list = {1,2,3}; executorservice executor = executors.newcachedthreadpool(); list<futuretask<string>> futuretasks = new arraylist<>(); for(int i=0;i<list.length;i++){ int[] list1 = list; list1[i] = list1[i]*2; jsonobject jsonobject = new jsonobject(); jsonobject.put("key", list1); futuretasks.add(new futuretask<string>(new queryexecutor(jsonobject))); } for(int n=0;n<futuretasks.size();n++){ executor.submit(futuretasks.get(n)); } for(int n=0;n<futuretasks.size();n++){ try { system.out.println(futuretasks.get(n).get()); } catch (interruptedexception e) { e.printstacktrace(); } catch (executionexception e) { e.printstacktrace(); } { executor.shutdown(); } } } } class queryexecutor implements callable<string> { private jsonobject jsonobject; public queryexecutor(jsonobject jsonobject){ system.out.println("jsonobject="+jsonobject); this.jsonobject = jsonobject; } @override public string call(){ string result = jsonobject.tostring(); return result; } }
i think maybe async , method call() refer object problem.
executorservice , futuretask.
as reminder arrays in java objects.
your problem same object referencing see below snippet of code
int[] list = {1,2,3}; int[] list1 = list; list1[i] = list1[i]*2;
when update reference list1 list gets updated because point same object internally , hence array passed below call method in furture reference same.
try changing from
int[] list1 = list;
to
int[] list1 = arrays.copyof(list,list.length);
run , see if meets expectations
Comments
Post a Comment