0

What really is Atomic? since I have to choose some language to frame my question more clearly I would choose Java. I know that atomic means do everything or just rollback/do nothing. so say I have the following

public class Myclass {

    private boolean progress;

    public void setProgress(boolean progress) {
        this.progress = progress;
    }

    public boolean getProgress() {
       return progress;
    }

}

Now which of the following are thread-safe or atomic or both ? please treat each new line as a separate piece of code

     -------------------
     getProgress(); // 
     ------------------

     ----------------------
     setProgress(true); //
     ----------------------

     -------------------
     getProgress()
     setProgress();
     -------------------

     --------------------
     setProgress();
     getProgress();
     --------------------

Which of these cases would make sense to use AtomicReference in java?

user1870400
  • 6,028
  • 13
  • 54
  • 115
  • Since `progress` is not `volatile`, the class is not thread-safe. When this is done, the class should be thread-safe. – Turing85 May 28 '16 at 19:19
  • As for atomic operations: The [Oracle Tutorial about Atomic Access](https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html) defines exactly two atomic operations: the reads and writes of any primitive field and reference field, except for `long`s and `double`s, as well as the reads and writes on `volatile` fields. – Turing85 May 28 '16 at 19:28
  • @Turing85, the `AtomicXxxxxxx` classes have some additional atomic operations beyond just those two. For example, `atomic.compareAndSet(expected, new)` which tests whether the variable equals `expected` and if so, sets it to `new`, all in a single atomic step. – Solomon Slow May 28 '16 at 19:37
  • @Turing85 We're talking at different levels of abstraction. I'm talking about the Java programming language, you're talking about hardware instructions. I've written a fair amount of code in my time where I was concerned about specific sequences of hardware instructions, but none of it was written in Java. – Solomon Slow May 28 '16 at 19:51

1 Answers1

2

From this:

What operations in Java are considered atomic?

I'd say none of them is atomic, since function call is not an atomic operation. But once you are in a function, assigning a boolean is atomic (just that line), returning it isn't.

For thread safety take a look at this:

Are java getters thread-safe?

Basically the old value of "progress" maybe cached inside cpu, so even if assigning it a new value was atomic (just that = line again) without a synched assignment (AtomicBoolean or synchronized getter/setter) it is thread-safe however there can be memory consistency errors so you may want to declare that variable volatile so other threads can see the most updated value.

Community
  • 1
  • 1
uylmz
  • 1,480
  • 2
  • 23
  • 44