[fpc-other] Felipe: Java and multi-threading

Graeme Geldenhuys mailinglists at geldenhuys.co.uk
Fri May 26 16:56:56 CEST 2017


Hi Felipe,

 > This simple program never ends if you delete the volatile keyword (I
 > tested here in Windows):

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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: FelipeTestThread.java
Type: text/x-java
Size: 953 bytes
Desc: not available
URL: <http://lists.freepascal.org/pipermail/fpc-other/attachments/20170526/0f1e085a/attachment.java>


More information about the fpc-other mailing list