java - safe publication, argument passing -
i have 2 threads, each has own counter: thread has countera, thread b has counterb. each thread has use both counters: thread has use countera , counterb, thread b has use both. using atomicinteger , share counters between 2 threads passing them arguments threads , each thread stores 2 counters in private fields.
// ... atomicinteger countera = new atomicinteger(0); atomicinteger counterb = new atomicinteger(0); thread ta = new thread(new runnablea(countera, counterb)); thread tb = new thread(new runnableb(countera, counterb)); // ... in constructor of runnablea ... runnablea(atomicinteger countera, atomicinteger counterb) { this.countera = countera; this.counterb = counterb; } //... // same runnableb
is safe publishing of 2 counters? safe-publishing necessary because reference object not safe enough share object between threads. how can achieve safe-publishing in case?
thanks in advance.
the term "safe publication" not applicable this. safe publication publication of state created in constructor. in example, atomicinteger
objects created before constructor called.
if other type used, may or may not safe depending on whether , how countera
, counterb
variables published. however, with counters implemented atomicinteger
objects, don't need worry publication. atomic / thread-safe, irrespective how published. possible concern might publication of state of instance variables. cannot tell whether occurs without looking @ rest of class. example:
- are variables
final
orvolatile
? - if non-volatile , non-final, access them synchronized?
- are thread-confined after
run()
called?
note runnables instantiated in current thread, not in threads created when (and if) ta.start()
, tb.start()
called. when start()
called, there happens-before between current thread's start()
call , new thread's run()
call. means safe publication of variables child thread guaranteed. publication of variables other threads of concern.
Comments
Post a Comment