Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set the priority of the background thread used by a SwingWorker?

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?

like image 438
Clinton Avatar asked Apr 16 '12 15:04

Clinton


3 Answers

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.

like image 97
Jason Braucht Avatar answered Nov 08 '22 17:11

Jason Braucht


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).

like image 44
Jim Avatar answered Nov 08 '22 17:11

Jim


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

like image 2
keuleJ Avatar answered Nov 08 '22 16:11

keuleJ