Working with Threads
In some cases, it may be desirable for an extension to create one or more threads
to allow it to perform some processing in the background, or to perform multiple
sets of processing concurrently. If your extension may need to create one or more
threads for some reason, then there are a number of things to keep in mind.
In general, extensions should not directly create threads (e.g., by creating
objects which extend java.lang.Thread , or by calling
new Thread(Runnable) ). Instead, the code to be invoked in that
thread should be in a class that implements the ServerThread
interface, and you should actually create the thread using the
ServerContext.createThread method. This provides a number of
benefits over other methods of creating threads, including:
-
It requires that a name be provided for the thread when it is created. If a
thread has a well-chosen name, then it can be very useful in helping to
understand the purpose of that thread when debugging problems.
-
Whenever a server thread is created, a stack trace is captured and stored
in the thread. Having information about the context in which a thread was
created may be very useful for debugging certain kinds of problems.
-
Server threads will have additional processing performed whenever they exit
(e.g., to ensure that they are not still holding any locks that have not been
properly released and could cause significant problems in the server).
-
Server threads are treated differently from non-server threads if they are
still running when the server is in the course of shutting down. In the event
that the shutdown process is taking too long, server threads more readily
interrupted that non-server threads to speed the shutdown process.
If your extension may create one or more threads, then it also needs to ensure
that those threads are properly shut down when the extension is disabled. In most
cases, the finalize {ExtensionType} method should be careful to
clean up any threads that were created by that extension. However, in some cases
it may be desirable to have a thread or set of threads shared across multiple
instances of an extension. In such cases, you will likely not want to destroy
those threads whenever any one of those instances are disabled if there may still
be other instances of the extension that are active. Rather, in this case you
will either want to use some kind of reference counter to only shut down the
threads when taking the last enabled instance of your extension out of service,
or you may simply wish to use something like a ServerShutdownListener
to ensure that the threads are notified when the server begins its shutdown
process.
|