Getting the value of a stream variable from outside

Lets say that the stream works as follows:

private boolean working = true; @Override public void run() { working = true; // do something working = false; .... } 

and in my main topic I constantly expose the state of work with

 while(threadClassObject.isWorking()) { System.out.println(threadClassObject.isWorking()); } 

will it work? I tried this example and it seems to work. But is there a way this can crash? What, for example, happens if a thread is in the process of changing work, while at the same time mainThread is trying to read it?

+6
source share
4 answers

The answer to your question is that it can work, but the code above is a risky code and can be interrupted any day. Try to make working volatile like

 private volatile boolean working = true; 

What eg happens if the thread is in the process of changing working while at the exact same time the mainThread tries to read it?

An assignment operation is an atomic operation. Therefore, if you have one processor, two threads can never collide when accessing a variable. If you have more than one processor, two threads may collide when accessing the variable. In both cases, volatile will make sure that this value is visible to other threads.

NOTE: volatile is good in your situation, but if you have more complex data for stream exchange, try exploring this.

Edit:

Adding a comment is also part of Soln. to make it more understandable.

Basically bcoz optimization at the processor level, the values ​​changed my one thread, may not have been visible to another. A good example is ccu cache bcoz optimization, values ​​are never reflected in bars where another stream can be read. Volatile reports that this variable value can be changed outside the current thread area, so this optimization is not performed ...

+6
source

You might also want to take a look at something to do with your fluent loop in your main thread:

The current implementation will continue to spin, not leaving a lot of processor time for your threads executing run() (or anyone else on the system, for that matter).

+3
source

You need to either use synchronization or AtomicBoolean to be thread safe. What you have in the code seems to work, but it is possible that when checking the boolean it will not be correct, so you will see unexpected results.

+1
source

No, there is no need to block primitive types such as boolean. If "work" was an object, you need to use synchronized blocks.

0
source

Source: https://habr.com/ru/post/909912/


All Articles