-3

I want to do something like this

while (true) {
    if (my_boolean) {  //my_boolean is being updated by other threads
        do something;
        break;
    }
    do something else;
} 

my problem is, my_boolean is being updated by another method in another thread. Sometimes such updates can be captured, sometimes not. Is there any consistent way to work around this?

3
  • Use AtomicBoolean Commented Sep 2, 2020 at 15:32
  • Or make the boolean volatile. Commented Sep 2, 2020 at 17:10
  • Downvoted. Check any java multithreading tutorial. Or search in StackOverflow before posting a question. This has been asked many times. Commented Sep 3, 2020 at 10:29

1 Answer 1

1

You can declare that boolean as volatile.

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

3 Comments

You don't have to. There are other ways to achieve the same effect.
This might also lead to a race condition if there are multiple threads that write that variable.
@Andy Turner: I don't see your point. I didn't say that my solution is the only possible one. Okay, the word "must" might get misunderstood.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.