0

I have thread A and Thread B , what would happen if A reads an int value in A(itself) to check a condtion , while B is writing to the same value at the same time would an error occur ? or just desynchronization ?

2
  • 2
    Writes to int are atomic. In fact, in practice, writes to long are atomic too - but not guaranteed to be. So the write is atomic, but not visible. Commented Sep 13, 2014 at 17:14
  • What @BoristheSpider means by "atomic": When threads access an "atomic" variable with no synchronization, every read is guaranteed to get either the initial value, or a value that was stored by some other thread. When unsynchronized threads access something (usually an object) that is not atomic, there is no such guarantee: Thread A could see a "value" that is a mix of bits that were written by two or more different threads Commented Sep 15, 2014 at 0:59

2 Answers 2

1

What you've described is called a race condition. Each run of your program will have a different value stored in Thread A's memory where the result of the read is stored, all depending on the order of operations executed.

Sign up to request clarification or add additional context in comments.

Comments

1

No error, just unpredictable results. For that kind of operation use AtomicInteger or implement locking mechanism.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.