Re: how to make this code thread safer?
Jim Janney wrote:
The simplest and least error prone approach is to declare both methods
as synchronized, e.g.
synchronized public void doThis()
synchronized public void checkSomething()
www wrote:
This is equal to running my program in single thread. Am I correct?
What do you mean by "equal"? It's not the same as running in a single
thread, no, and nor is it always going to be enough for every
concurrent situation. Whether it's as safe as running in a single
thread depends on the details of the situation, but for this simple
situation it seems to be. Pete alluded to risks with this approach
upthread.
More specifically, how can I make sure that checkSomething() is finished
at the top of doThis()?
With the simple approach shown, you can be sure that
'checkSomething()' and 'doThis()' are not executing simultaneously
within the same instance.
You need to learn to think in terms of concurrent programming, which
takes a bit of time. One trick is to think in terms of "critical
sections". Those are parts of code that access the same data, so in a
concurrent environment they can interfere with each other unless
you're careful. To be careful, you apply 'synchronized' or 'volatile'
or a raft of other techniques. A critical section is a shortest piece
of code that operates on the shared data as a unitary operation. The
collection of critical sections is the collection of pieces of code
that have to honor the same synchronization mechanism.
By the way, this is for read or write. You cannot synchronize on,
say, just the write sections and expect unsynchronize read sections to
work correctly.
Another trick is to master the Java concept of /happens-before/. This
is the set of rules about what changes threads can see that were made
by other threads. It's a good trick because once you get the concept,
you can reason about whether changes will be visible or conflict
between threads.
--
Lew