I am working on a graph ( nodes and vertices ) partitioning algorithm.
I use multiple threads to try and identify certain regions inside the graph.
Once a node has been identified as a part of a region, I set a boolean marked
to true for the node object.
Multiple threads can attempt to mark the same node at the same time.
Currently I use synchronization to ensure nothing bad happens.
However since I never read the value of marked till after all the threads have finished processing. Would it be possible for me to get rid of the synchronization code? In other words can anything go wrong when concurrently writing to a boolean variable?
There are several patterns on how to allow multiple threads to write to the same file. the ReaderWriterLock class is invented for this purpose. Another classic is using semaphors and the lock statement to lock a shared resource.
Even though the variable is not currently being written to, previous writes to the variable may not yet be visible to all threads. This means two threads can read the same value and get different results creating a race condition.
A data race is a state, in which at least two threads access shared data at the same time, and at least one of the threads is a writer. A critical section is a section of the code, which not more than one thread should access at any point in time.
A thread can execute a function in parallel with other threads. Each thread shares the same code, data, and files while they have their own stack and registers.
can anything go wrong when concurrently writing to a boolean variable?
Yes and no. Certainly the resulting value won't be somehow corrupted however it is going to be non-deterministic on which of the updates gets set on the field and when these updates are seen by other threads -- if at all.
If you have multiple threads making decisions using the value of this boolean, you have to at some point provide memory synchronization. Making the field volatile
costs very little and unless you have evidence that it is a performance problem, not having the field be volatile
is most likely premature optimization. If you are comparing and setting then an AtomicBoolean
is recommended which wraps a volatile boolean
and provides higher level methods like compareAndSet(...)
.
In theory, no, but I wouldn't mind declaring the variable volatile
. Volatile keyword ensures atomic access.
(Provided that the order of the writes do not matter and all reads occur after all writes.)
No, nothing could go wrong when multiple threads write to the same boolean value, but there can be a problem of reading the value (even a long time) later in a different thread. You should at least mark the variables as volatile
to prevent the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With