java - Why is this code thread safe? -


i preparing ocp exam , found question in mock exam:

given:

class calculator {     private atomicinteger = new atomicinteger();     public void add(int value) {         int oldvalue = i.get();         int newvalue = oldvalue + value;         system.out.print(i.compareandset(oldvalue,newvalue));     }     public int getvalue() {         return i.get();     } } 

what make class thread safe?

and surprisingly, me, answer is: "class calculator thread-safe"

it must have not understood correctly concept. understanding, class thread safe when methods work expected under thread concurrency. now, if 2 thread call @ same time getvalue(), call add() passing different value, , call getvalue() again, 'second' thread won't see value passed increased.

i understand oldvalue , newvalue local variables stored in method stack, doesn't prevent second call compareandset find oldvalue not current value , won't add newvalue.

what missing here?

according jcip

a class thread-safe if behaves correctly when accessed multiple threads, regardless of scheduling or interleaving of execution of threads runtime environment, , no additional synchronization or other coordination on part of calling code.

although there no definition of thread-safety , no specification of class, in opinion, sane definition of add method in calculator class "correct" if value of atomicinteger i increased in case, "regardless of scheduling or interleaving of execution".

therefore, in opinion, class not thread-safe definition.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -