Discussion:
[fpc-other] Felipe: Java and multi-threading
Graeme Geldenhuys
2017-05-26 14:56:56 UTC
Permalink
Hi Felipe,
This simple program never ends if you delete the volatile keyword (I
Yes, I got the same behaviour as you, using Java 1.8 under FreeBSD. But
I immediately saw your problem. You are accessing the same data from
more than one thread. That has always been a big NO-NO in any
programming language.

Using the synchronized code blocks to protect the common data or actions
being executed I get this as output.

[threads]$ java FelipeTestThread
Thread 2 finishing
Thread 1 finished. Counted up to 2205390
[threads]$

It works, just like it does when the "volatile" keyword is used.

Attached is the corrected version of your sample application without the
volatile keyword. It is worth noting that using volatile is faster, but
also has its limits (ie: you can't protect a whole block of code or
actions).

But the bottom line is, you tried to access common data from multiple
threads, without trying to protect that data. Not the way to go!

Regards,
Graeme
--
fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal
http://fpgui.sourceforge.net/

My public PGP key: http://tinyurl.com/graeme-pgp
Graeme Geldenhuys
2017-05-26 15:50:14 UTC
Permalink
Post by Graeme Geldenhuys
Attached is the corrected version of your sample application without the
volatile keyword. It is worth noting that using volatile is faster, but
also has its limits (ie: you can't protect a whole block of code or
actions).
To add to this, there is also a memory access effect between volatile
and synchronize. For a detailed explanation, take a look the marked
"correct answer" in this StackOverflow topic:


https://stackoverflow.com/questions/3519664/difference-between-volatile-and-synchronized-in-java



Regards,
Graeme
--
fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal
http://fpgui.sourceforge.net/

My public PGP key: http://tinyurl.com/graeme-pgp
_______________________________________________
fpc-other maillist - fpc-***@lists.freepascal.org
http://lists.freep
Loading...