Java Reference
In-Depth Information
LISTING 9-5: (continued)
public void run() {
Although it's just one line less than the previous listing, Listing 9‐5 delegates the creation and starting
of the thread to the ExecutorService and only deals with servlet‐specii c code.
Asynchronous servlets are easier to understand and code and have an immediate effect on runtime
behavior because it directly switches to the asynchronous execution model. Asynchronous servlets
provide a clean implementation without a lot of boilerplate code.
You can use the asynchronous pattern almost anywhere where it is required to return a response
before all the execution is complete. This approach can vary from executing the less important
functions of the application asynchronously, such as logging or keeping the user informed about a
time‐consuming operation. Asynchronous programming makes the critical execution path shorter
while delegating subtasks to other threads. The result is better response times.
Asynchronous annotation is a simple way to implement asynchronous methods or convert existing
ones. Each method marked with the asynchronous annotation runs in a separate thread without
locking the current thread's execution. This behavior is a perfect match for conditions that do not
affect the main execution cycle but need to be performed on the back end. Examples include logging
and maintenance resources.
You can use asynchronous servlets in almost all modern web apps. Asynchronous servlets provide
nonblocking asynchronous behavior without a special need for AJAX. Asynchronous servlets can help
when a server‐based push operation is needed, such as updating information or delivering a message.
Because each asynchronous execution requires a new thread, the Java Virtual Machine (JVM) needs
to perform more context switches as more asynchronous methods are implemented. A large number
of context switches cause thread starvation and result in poorer performance than a synchronous
Imagine that you are reading one book. Between reads, you must remember the story, the
characters, and the last page you've read. If you're reading two topics at the same time, you may
i nish the second shorter book without needing to i nish the longer one you started. The time spent
changing context from one book to the other is acceptable.
Reading six topics in parallel would be challenging. It may require so many context changes that
you may not be able to i nish any of the topics in the expected time and end up changing from one
book to the other without making much progress in any of them.
Search WWH ::

Custom Search