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
class FelipeTestThread {

	//volatile keyword not needed any more
	private boolean running = true;

	public void test() {
		// thread 1
		new Thread(new Runnable() {
			public void run() {
				int counter = 0;
				while (isRunning()) {
					counter++;
				}
				System.out.println("Thread 1 finished. Counted up to " + counter);
			}
		}).start();
		
		// thread 2
		new Thread(new Runnable() {
			public void run() {
				// Sleep for a bit so that thread 1 has a chance to start
				try
				{
					Thread.sleep(100);
				} catch (InterruptedException ignored) {
					// do nothing
				}
				System.out.println("Thread 2 finishing");
				//running = false;
				stopRunning();
			}
		}).start();
	}
	
	public static void main(String[] args) {
		new FelipeTestThread().test();
	}
	
	public void stopRunning() {
		synchronized(this) {
		  running = false;
		}
	}
	
	public boolean isRunning() {
		synchronized(this) {
			return (running == true);
		}
	}
}
_______________________________________________
fpc-other maillist  -  fpc-other@lists.freepascal.org
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-other

Reply via email to