java - Using volatile keyword with wrapper classes -
in class on java concurrency advised utilize next code counter in multithreaded application
private volatile int count; i asking myself if utilize volatile keyword wrapper class integer instead of primitive type int (see below):
private volatile integer count; would right utilize integer wrapper class in case?
strictly speaking, correct. if 1 thread sets new count, every other thread reading new value.
you run issues if 2 threads write value @ same time since there never guarantee value lastly read counter value when go write counter. example, if have 2 threads , counter starting off @ 0.
thread 1: int temp = count.intvalue(); //temp = 0; thread 2: int temp = count.intvalue(); //temp = 0; thread 1: count = new integer(temp+1); //count = 1; thread 2: count = new integer(temp+1); //count = 1; as can see, incremented counter twice value increased 1. same behavior can occur if alter command to
count = new integer(count.intvalue() + 1); since jvm still needs read in value, increment it, , write out, each of @ to the lowest degree 1 cycle.
to avoid this, either utilize atomicinteger (which not need volatile), suggested @chrylis, or utilize synchronization and/or locks create sure never have 2 threads writing count.
java concurrency
No comments:
Post a Comment