Java doesn't break when running on Linux

I found a cryptic issue with Java code for homework. A program for friends is an application that at the beginning:

public void run() { vm.setVisible(true); while(!end); System.out.println("Finish"); vm.setVisible(false); } 

The logical "end" is false at run time and when the user exits the application:

 private class CloseSys implements ActionListener { public CloseSys() {super();} public void actionPerformed(ActionEvent e) { System.out.println("CLOSE SYS"); System.out.println("end: "+end); end = true; System.out.println("end: "+end); } } 

Println shows that the value of "end" changes to true and logically on my friend computer (MacOS), when the application ends too.

The problem is that on my computer (Ubuntu Linux) println also shows up as a change in value, but the time does not end (the value of "Finish" println is never reached). The funny thing is that we put fingerprints at the time ... then it works!

+6
java linux while-loop
source share
4 answers

end must be volatile since it is split between two threads!

+3
source share

Several other people mentioned that they must be unstable. The only thing that no one has mentioned yet is that you are "busy waiting," which is wrong, wrong, wrong. If you want to wait until something happens in another thread, you should use synchronization locks or Semaphores .

+5
source share

Try changing the end volatile variable - you have been bitten by the multithreading problem (and you have a multi-core processor).

Here is some information about this: http://www.javamex.com/tutorials/synchronization_volatile_when.shtml

+2
source share

It looks like a thread issue.

Try declaring end as volatile or it is better to use CountDownLatch , as this avoids processor hangs:

 private CountDownLatch latch; public void run() { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { vm.setVisible(true); } }); try { latch.await(); System.out.println("Finish"); } finally { SwingUtilities.invokeAndWait(new Runnable() { public void run() { vm.setVisible(false); } }); } } catch (InterruptedException ex) { System.out.println("Interrupt"); Thread.currentThread().interrupt(); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } private class CloseSys implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("CLOSE SYS"); latch.countDown(); } } 

Note the use of invokeAndWait to change the visibility of a window from a stream other than EDT.

+2
source share

All Articles