java - Thread Safety - declaring a new thread inside method local block -
i curious if following code thread-safe:
public static void methoda () { // given mutableobject not thread-safe (no lock/synchronization used) mutableobject mo = new mutableobject(); mo.setsomevalue(100); // set int value // mutablelist variable must final in order pass thread block final list<mutableobject> mutablelist = new arraylist<mutableobject>(); mutablelist.add(mo); thread t = new thread() { @override public void run() { (mutableobject e : mutablelist) { e.printintvalue(); // print 100 or 0? } } } t.start(); }
so, here question. not sure whether contents reachable* "mutablelist" reference visible new thread though there no explicit synchronization/locking used. (visibility issue) in other words, new thread print 0 or 100? print 0 if not see value 100 set main thread 0 default primitive value of int data type.
ie. "contents reachable" means:
- the int value 100 held mutableobject
- the reference mutableobject held arraylist
thanks answering.
this code thread-safe because there not way other thread access the same objects because available inside methoda()
, in method run()
of thread. both not change data.
thread safety problems appear when @ least 2 threads operate same data. not case.
how make code thread-unsafe? there several ways.
add line
mo.setsomevalue(100);
after callingt.start()
. means after staring thread there 2 threads (your main thread , other thread) operate same objectmo
. no cause exceptions.add line
mutablelist.remove(0)
. may causeconcurrentmodificationexception
if thread starts enough , manages enter loop before main thread arrives remove instruction.
Comments
Post a Comment