java - Set non-primitive types when returning from thread -
my question is: why setting non-primitive type work when returning threads ?
the following works:
final int[] newtask = new int[1]; try{ thread thread = new thread(new runnable(){ @override public void run(){ newtask[0] = somemethod(); return; } }); thread.start(); thread.sleep(3000); if(thread.isalive()){ thread.interrupt(); newtask[0] = null; } }catch(interruptedexception ie){ log.error("timeout", ie); } the following doesn't:
final int newtask; try{ thread thread = new thread(new runnable(){ @override public void run(){ newtask = somemethod(); return; } }); thread.start(); thread.sleep(3000); if(thread.isalive()){ thread.interrupt(); newtask = null; } }catch(interruptedexception ie){ log.error("timeout", ie); } non-primitives variables work when returning thread primitives don't. why ?
in first case, newtask reference array. reference cannot changed, because final. content of array can modified, because array not immutable.
in second case, newtask primitive value. can't changed, because final.
a simpler example of same behavior this:
final stringbuilder buf = new stringbuilder(); buf.append('x'); /* modified mutable object; no problem. */ buf = new stringbuilder(); /* compiler error: can't reassign final var */ it has nothing threads, or differences between primitive values , reference types.
Comments
Post a Comment