multithreading - Are java variables themselves thread safe? When updating variables? -


this question has answer here:

suppose have 2 threads updating object, , 1 thread reading object no synchronization. obviously, run condition. however, wondering if variable can partially written.

public class commonobject extends object {     static int membervar=-1; }  public class input1thread extends thread {        public void run()        {         while(true)             commonobject.membervar = 1     } }  public class input2thread extends thread {        public void run()        {         while(true)             commonobject.membervar = 2;     } }  public class outputthread extends thread {        public void run()        {         while(true)             system.out.println("commonobject.membervar"+ commonobject.membervar);     } }   

i assume value printed out either 2 or 1. however, wondering if possible variable might halfway set?

i used primitives example, answer objects also, if different.

it depends on type of variable.

doubles , longs (the 2 64-bit types in java) allowed word-tear if they're not volatile, while other types (including references) may never tear. word tearing give behavior you're worried about: of bytes old value, of them new value, , overall result value that's neither old nor new.

this specified in jls 17.7:

for purposes of java programming language memory model, single write non-volatile long or double value treated 2 separate writes: 1 each 32-bit half. can result in situation thread sees first 32 bits of 64-bit value 1 write, , second 32 bits write.

writes , reads of volatile long , double values atomic.

writes , reads of references atomic, regardless of whether implemented 32-bit or 64-bit values.

of course, introducing data races introduces whole host of issues; question targeted @ word tearing, i'm addressing here, except note "just because can, doesn't mean should." should careful analyze each data race have , prove it's benign (as of them -- string.hashcode's caching of values).


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -