Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-other / 2017-05

Re: Felipe: Java and multi-threading

2 messages · 1 person ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Graeme Geldenhuys

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
Graeme Geldenhuys
to Graeme Geldenhuys
Graeme Geldenhuys wrote
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