Note: These pages are being reviewed.
I need to run some code on a background thread. Can the platform help me?
First, ask yourself why you need to do this and if it is really necessary. Generally there is only one reason: You are doing something takes some time (file I/O, computing something large and complicated, talking to a network socket) that will block the UI.
NetBeans contains a thread pool
org.openide.util.RequestProcessor. (You can use the thread pools that exist today in
java.util.concurrent but it is more typical to use
RequestProcessor.) There is a general purpose built-in thread pool -
RequestProcessor.getDefault(). You can use that for things that only happen once in a while; otherwise you are probably better off creating your own instance of
RequestProcessor. There is a FAQ item about how to know when to do which. In its most simple usage,
RequestProcessor.post() is called with a
Runnable. The call returns a
RequestProcessor.Task which you can use to monitor the status of the task and listen to task finish among other.
Note that if you are doing something in the background, you may want to use the Progress API to show a progress indicator in the status-bar (or use it to put up a modal progress dialog if the UI really needs to be blocked - use with care, only when really necessary).
Remember that if you are running more threads than you have processors (or cores) - and your OS is probably using some as well - then when you ask to multi-thread, you are asking your CPU to divide the time of the CPUs you have between more virtual threads. And switching the context a CPU is working in - sending it off to some other memory space and set of instructions, and then another - takes time. So heavy use of multi-threading, especially on single CPU machines, can slow things down rather than speed them up. If you can make your code run faster, do that first.
Apache Migration Information
The content in this page was kindly donated by Oracle Corp. to the Apache Software Foundation.
This page was exported from http://wiki.netbeans.org/DevFaqThreading , that was last modified by NetBeans user Dsimonek on 2009-12-03T15:28:32Z.
NOTE: This document was automatically converted to the AsciiDoc format on 2018-02-07, and needs to be reviewed.