AtomicInteger and volatile [duplicate]
Asked Answered
K

5

35

I know volatile allows for visibility, AtomicInteger allows for atomicity. So if I use a volatile AtomicInteger, does it mean I don't have to use any more synchronization mechanisms?

Eg.

class A {

    private volatile AtomicInteger count;

    void someMethod(){
        // do something
        if(count.get() < 10) {
            count.incrementAndGet();
        }
}

Is this threadsafe?

Keir answered 15/1, 2013 at 13:12 Comment(9)
What do you mean by "threadsafe" here? There's no guarantee that the above code will mean count never goes above 10, for example - multiple threads could call intValue(), and then all call incrementAndGet().Teratism
Exactly, so will this work? if(count.get() <10){ count.incrementAndGet(); } I think I still need a layer of synchronization around, isn't it?Keir
I can't give an answer about what will "work" until you give requirements. Will it compile? Yes. Will it avoid any increments getting lost? Yes. Will it do what you want? I can't tell.Teratism
I meant thread-safe? Meaning will it be safe from lost updates?Keir
Yes - but you could end up with a count which is larger than 10.Teratism
Yep, understood clearly, so would still require a synchronized block around AtomicInteger. Thanks a lot @JonSkeetKeir
Not necessarily. It depends on your requirements, which you still haven't given. Using compareAndSet in a loop, you could ensure that you never go above 10. But I'm not going to start writing sample code to help you solve a problem that you haven't specified clearly enough.Teratism
@JonSkeet, the requirements are simple. It should be threadsafe, now what do you mean by that? IMHO, since I am doing a simple check-then-act, it would "appear" that I don't want somebody to get hold of count >10 and this happens in a multi-threaded env.("obviously") . Thanks for all your answers though.Keir
No, none of this is obvious. There are various situations where it might be fine to go above a soft limit, but not fine to lose the number of times you have gone over that limit. Given your actual requirements, I suggest you ask a new question with those requirements, leaving this one as it is.Teratism
T
75

I believe that Atomic* actually gives both atomicity and volatility. So when you call (say) AtomicInteger.get(), you're guaranteed to get the latest value. This is documented in the java.util.concurrent.atomic package documentation:

The memory effects for accesses and updates of atomics generally follow the rules for volatiles, as stated in section 17.4 of The Java™ Language Specification.

  • get has the memory effects of reading a volatile variable.
  • set has the memory effects of writing (assigning) a volatile variable.
  • lazySet has the memory effects of writing (assigning) a volatile variable except that it permits reorderings with subsequent (but not previous) memory actions that do not themselves impose reordering constraints with ordinary non-volatile writes. Among other usage contexts, > - lazySet may apply when nulling out, for the sake of garbage collection, a reference that is never accessed again.
  • weakCompareAndSet atomically reads and conditionally writes a variable but does not create any happens-before orderings, so provides no guarantees with respect to previous or subsequent reads and writes of any variables other than the target of the weakCompareAndSet.
  • compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.

Now if you have

volatile AtomicInteger count;

the volatile part means that each thread will use the latest AtomicInteger reference, and the fact that it's an AtomicInteger means that you'll also see the latest value for that object.

It's not common (IME) to need this - because normally you wouldn't reassign count to refer to a different object. Instead, you'd have:

private final AtomicInteger count = new AtomicInteger();

At that point, the fact that it's a final variable means that all threads will be dealing with the same object - and the fact that it's an Atomic* object means they'll see the latest value within that object.

Teratism answered 15/1, 2013 at 13:19 Comment(7)
Ok, I have amended the question a little bit, can u please explain if that would hold good?Keir
@anirbanchowdhury: Why would you use intValue() rather than get?Teratism
Rite, my mistake, have updated the original question to get()Keir
Thanks a ton.Exactly this is what I was looking forAntenna
The real field holding the value in an AtomicInteger is, unsurprisingly, volatile!Birefringence
final != static right?Gale
@AlwynSchoeman: Indeed, they're entirely orthogonal. Something can be final but not static, or static but not final, or both, or neither.Teratism
R
6

I'd say no, it's not thread-safe, if you define thread-safe as having the same result under single threaded mode and multithreaded mode. In single threaded mode, the count will never go greater than 10, but in multithreaded mode it can.

The issue is that get and incrementAndGet is atomic but an if is not. Keep in mind that a non-atomic operation can be paused at any time. For example:

  1. count = 9 currently.
  2. Thread A runs if(count.get() <10) and gets true and stopped there.
  3. Thread B runs if(count.get() <10) and gets true too so it runs count.incrementAndGet() and finishes. Now count = 10.
  4. Thread A resumes and runs count.incrementAndGet(), now count = 11 which will never happen in single threaded mode.

If you want to make it thread-safe without using synchronized which is slower, try this implementation instead:

class A{

final AtomicInteger count;

void someMethod(){
// do something
  if(count.getAndIncrement() <10){
      // safe now
  } else count.getAndDecrement(); // rollback so this thread did nothing to count
}
Radiothorium answered 30/8, 2014 at 6:45 Comment(0)
P
2

To maintain the original semantics, and support multiple threads, you could do something like:

public class A {

    private AtomicInteger count = new AtomicInteger(0);

    public void someMethod() {

        int i = count.get();
        while (i < 10 && !count.compareAndSet(i, i + 1)) {
            i = count.get();
        }

    }

}

This avoids any thread ever seeing count reach 10.

Porphyria answered 2/12, 2014 at 13:3 Comment(0)
F
1

Answer is there in this code

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/atomic/AtomicInteger.java

This is source code of AtomicInteger. The value is Volatile. So,AtomicInteger uses Volatile inside.

Farcical answered 23/11, 2014 at 7:5 Comment(0)
M
0

Your query can be answered in 2 parts, because there are 2 questions in your query :

1) Referring to Oracle's tutorial documentation for Atomic variables : https://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html

The java.util.concurrent.atomic package defines classes that support atomic operations on single variables. All classes have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features, as do the simple atomic arithmetic methods that apply to integer atomic variables.

So atomic integer does use volatile inside, as other answers here have mentioned. So there's no point in making your atomic integer volatile. You need to synchronize your method.

You should watch John Purcell's free video on Udemy , where he shows the failure of volatile keyword when multiple threads are trying to modify it. Simple and beautiful example. https://www.udemy.com/course/java-multithreading/learn/lecture/108950#overview

If you change the volatile counter in John's example into an atomic variable, his code is guaranteed to succeed without using sunchronized keyword like he has done in his tutorial

2) Coming to your code : Say thread 1 kicks into action and "someMethod" does a get and checks for size. It is possible that before getAndIncrement executes(say, by thread 1) , another thread (say thread 2)kicks in and increases the count to 10, and gets out; after which, your thread 1 will resume and increase count to 11. This is erroneous output. This is because your "someMethod" is not protected in anyway from synhronization problems. I would still recommend you to watch john purcell's videos to see where volatile fails , so that you have a better understanding of the keyword volatile. Replace it with atomicinteger in his example and see the magic.

Msg answered 29/8, 2019 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.