I have just started to read and work through the examples in Jason Hunter's
Java Servlet Programming. I can't get Example 3-6 p. 52 to work and this is driving me crazy! I modified the code a little, but it is esentially the same. The example is to demonstrate that servlets can execute between access.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PrimeSearcher extends HttpServlet implements Runnable {
int count = 0;
long lastprime = 0;
Date lastprimeModified = new Date();
Thread searcher;
public void init() throws ServletException {
searcher = new Thread(this);
searcher.setPriority(Thread.MIN_PRIORITY);
searcher.start();
}
public void run() {
long candidate = 11L;
while(count < 1000) {
if(isPrime(candidate)) {
count++;
lastprime = candidate;
lastprimeModified = new Date();
}
candidate += 2;
try {
searcher.sleep(200);
}
catch (InterruptedException ignored) { }
}
}
private static boolean isPrime(long candidate) {
long sqrt = (long)Math.sqrt(candidate);
for(long i = 3; i<= sqrt; i+=2) {
if(candidate % i == 0) return false;
}
return true;
}
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 for first prime...");
} else {
out.println("The last prime discovered is " + lastprime);
out.println(" at " + lastprimeModified);
}
}
public void destroy() {
// searcher.stop();
}
}
This should find primes right away and accessing the servlet quickly for the second time I should find that a prime has been found. All I get is "still searching". At this point I can't tell what is wrong. Any help would be appreciated. Thanks.