Search code examples
javaswingconcurrencyblockingswingworker

SwingWorker synchronized method queue blocking or what?


Theoretical question. If I have two SwingWorkers and an outputObject with method

public void synchronized outputToPane(String output)

If each SwingWorker has a loop in it as shown:

//SwingWorker1
while(true) { 
     outputObject.outputToPane("garbage");
}
//SwingWorker2
Integer i=0;
while(true) {
     outputObject.outputToPane(i.toString());
     i++;
}

How would those interact? does the outputToPane method receive an argument from one thread and block the other one until it finishes with the first, or does it build a queue of tasks that will execute in the order received, or some other option?

The reason I ask:
I have two threads that will be doing some heavy number crunching, one with a non-pausable data stream and the other from a file. I would like them both to output to a central messaging area when they hit certain milestones; however, I CANNOT risk the data stream getting blocked while it waits for the other thread to finish with the output. I will risk losing data then.


Solution

  • synchronized only guarantees mutual exclusion. Is not fair, which in practice means that your workers might alternate quite nicely, or the first one might get precedence and block the second one completely until finished, or anything between.

    See Reentrantlock docs for more about fairness. Maybe you could consider using it instead of synchronized. Probably even better alternative would be using a Queue.