Background Processing
Servlets can do more than simply
persist between accesses. They can also execute
between accesses. Any thread started by a servlet can continue
executing even after the response has been sent. This ability proves
most useful for long-running tasks whose incremental results should
be made available to multiple clients. A background thread started in
init() performs continuous work while
request-handling threads display the current status with
doGet(). It’s a similar technique to that
used in animation applets, where one thread changes the picture and
another paints the display.
Example 3.6 shows a servlet that searches for prime numbers above one quadrillion. It starts with such a large number to make the calculation slow enough to adequately demonstrate caching effects—something we need for the next section. The algorithm it uses couldn’t be simpler: it selects odd-numbered candidates and attempts to divide them by every odd integer between 3 and their square root. If none of the integers evenly divides the candidate, it is declared prime.
Example 3-6. On the hunt for primes
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PrimeSearcher extends HttpServlet implements Runnable { long lastprime = 0; // last prime found Date lastprimeModified = new Date(); // when it was found Thread searcher; // background search thread public void init(ServletConfig config) throws ServletException { super.init(config); // ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access