tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Juan Alvarez Ferrando <jaferra...@oviedo.syseca.es>
Subject Re: Expert advice needed
Date Tue, 09 May 2000 11:50:00 GMT

Some more info also from JAVA Servlet Programming:

At page 65 there's an example showing how a servlet can start a thread
that computes prime numbers while it serves requests for this
information:

...

public class PrimeSearcher extends HttpServlet implements Runnable {

    long lastprime = 0;
    Date lastprimeModified = new Date();
    Thread searcher;

    public void init(ServletConfig config) {
        super.init(config);
        searcher = new Thread(this);
        searcher.setPriority(Thread.MIN_PRIORITY);
        searcher.start();
    }

    public void run() {
        long candidate = 1000000000000001L;

        while (true) {
            if (isPrime(cadidate)) {
                lastprime = candidate;
                lastprimeModified = new Date();
            }
            candidate += 2;

            try {
                searcher.sleep(200);
            }
            catch (InterruptedException ignored) {}
        }
    }

    private static boolead isPrime(long candidate) {
        ....
    }

    public void doGet (HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
        res.setContentType("text/plain");
        PrintWriter out = res.getWriter();
        if (lastprime == 0) {
            out.println("Still searching...");
        } else {
            out.println("the last prime discovered was " + lastprime);
            out.println(" at " + lastprimeModified);
        }
    }

    public void destroy() {
        searcher.stop();
    }
}

You'll probably need to adapt this, so it can handle several computing
threads simultaneously and give each user her/his own state information.

One advice: BEWARE LOCKING RESOURCES.

Juan Alvarez Ferrando
Mime
View raw message