FileDocCategorySizeDatePackage
PrimeSearcher.javaAPI DocExample2109Thu Apr 05 01:21:02 BST 2001None

PrimeSearcher

public class PrimeSearcher extends HttpServlet implements Runnable

Fields Summary
long
lastprime
Date
lastprimeModified
Thread
searcher
Constructors Summary
Methods Summary
public voiddestroy()

    searcher.stop();
  
public voiddoGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)

    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 was " + lastprime);
      out.println(" at " + lastprimeModified);
    }
  
public voidinit()

                       // background search thread

       
    searcher = new Thread(this);
    searcher.setPriority(Thread.MIN_PRIORITY);  // be a good citizen
    searcher.start();
  
private static booleanisPrime(long candidate)

    // Try dividing the number by all odd numbers between 3 and its sqrt
    long sqrt = (long) Math.sqrt(candidate);
    for (long i = 3; i <= sqrt; i += 2) {
      if (candidate % i == 0) return false;  // found a factor
    }

    // Wasn't evenly divisible, so it's prime
    return true;
  
public voidrun()

    //               QTTTBBBMMMTTTOOO
    long candidate = 1000000000000001L;  // one quadrillion and one

    // Begin loop searching for primes
    while (true) {                       // search forever
      if (isPrime(candidate)) {
        lastprime = candidate;           // new prime
        lastprimeModified = new Date();  // new "prime time"
      }
      candidate += 2;                    // evens aren't prime

      // Between candidates take a 0.2 second break.
      // Another way to be a good citizen with system resources.
      try {
        searcher.sleep(200);
      }
      catch (InterruptedException ignored) { }
    }