0

today i found a pretty funny issue. Basically this code doesnt work if you remove the System.out.println. It never goes inside the if without it !!! (Thread is started from main class)

import java.util.LinkedList;
import java.util.Vector;
import java.util.Queue;



public class Matchmaking extends Thread{
    public static Vector onlinePlayers = new Vector();
    public static Queue<Player> queuedPlayers = new LinkedList<Player>();


    @Override
    public void run() {
        while(true){
            System.out.println(queuedPlayers.size());
            if(queuedPlayers.size() >= 2){
                new Matchmaking_GameFoundThreads(queuedPlayers.remove(),queuedPlayers.remove());
            }
        }
    }
}
Kores
  • 107
  • 1
  • 6
  • 2
    Concurrency or debugging issues? – keyser Aug 07 '15 at 23:19
  • What does `size()` do, exactly? – Reut Sharabani Aug 07 '15 at 23:23
  • returns how many players are queued (its code from a game). So every time there are 2+ players in queue it matches them together against each other – Kores Aug 07 '15 at 23:24
  • 1
    The reason why calling `System.out.println` makes this work, when `queuedPlayers` is non-volatile, is that the underlying methods of `PrintStream` are synchronized, which effectively forces the value of `queuedPlayers` to get fetched from main memory instead of cache. The accepted answer of [Loop doesn't see changed value without a print statement](http://stackoverflow.com/questions/25425130/loop-doesnt-see-changed-value-without-a-print-statement) gives an in-depth explanation. – Mick Mnemonic Aug 07 '15 at 23:59

2 Answers2

2

LinkedList is unsynchronized.

The changes to it in one thread might not be visible in another thread. Try using :

public static List<Player> queuedPlayers = 
     Collections.synchronizedList( new LinkedList<Player>() );
Anonymous Coward
  • 3,140
  • 22
  • 39
0

I solved it by making the Queue volatile. I am not sure if it's good to do so because I am not familiar with volatile's usage but it worked...

Kores
  • 107
  • 1
  • 6