Java – use volatile keyword with wrapper class

In Java concurrency classes, I recommend using the following code as counters in multithreaded applications

private volatile int count;

I asked myself if I could use the volatile keyword with the wrapper class integer instead of the original type int (see below):

private volatile Integer count;

Is it correct to use the integer wrapper class in this case?

Solution

Strictly speaking, this is correct If a thread sets a new count, each other thread reading it will get a new value

If two threads write values at the same time, problems will be encountered because there is no guarantee that the last value read for the counter is the value when the counter was written For example, if you have two threads and the counter starts at 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 you can see, you increment the counter twice, but the value only increases by 1 The same behavior occurs even if you change the command to

count =  new Integer(count.intValue() + 1);

Since the JVM still needs to read in values, increment and write out, each has at least one cycle

To avoid this, use @ chrylis's recommended atomicinteger (no volatile is required), or use synchronization and / or locking to ensure that 2 threads will never write to the count

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>