Question

In Java is there a way to set the priority for the thread that will be calling the doInBackground() method of a SwingWorker object?

In the Thread API there is a setPriority() method. The SwingWorker.execute() method schedules the swingworker for execution on a worker thread. I would like to have access to that worker thread to set it's priority.

From my understanding this worker thread comes from a default worker thread pool. Would the only way to handle this is to use my own executor?

Was it helpful?

Solution

The JDK7 SwingWorker javadoc hints that the designers did not intend for users to directly interact with or alter the background threads:

... the exact strategy of choosing a thread for any particular SwingWorker is unspecified and should not be relied on.

The implementation of SwingWorker.getWorkersExecutorService() seems to reinforce this idea as they've implemented it in a way that is not easily changed.

SwingWorker is a boilerplate solution to the typical case and you don't have a typical case. I'd suggest you write the code to handle running the background tasks instead of trying to hack SwingWorker to do what you want. That way whoever gets to maintain your code in the future (perhaps even yourself!) won't be left wondering why SwingWorker isn't behaving as expected.

OTHER TIPS

The only way I can think to do this is to have the execute method grab the current thread using Thread.currentThread(). You can then set the priority of this thread (provided the caller is allowed to).

As the SwingWorker is a Runnable, you can submit it to any java.util.concurrent.ExecutorService

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top