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:

  1. the int value 100 held mutableobject
  2. 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.

  1. add line mo.setsomevalue(100); after calling t.start(). means after staring thread there 2 threads (your main thread , other thread) operate same object mo. no cause exceptions.

  2. add line mutablelist.remove(0). may cause concurrentmodificationexception if thread starts enough , manages enter loop before main thread arrives remove instruction.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -