FileDocCategorySizeDatePackage
RunnableSolver.javaAPI DocExample3158Sat Jan 31 17:15:34 GMT 1998dcj.examples

RunnableSolver

public class RunnableSolver extends Object implements Solver, Runnable
Source code from "Java Distributed Computing", by Jim Farley. Class: RunnableSolver Example: 4-1 Description: A Solver that can be run within the body of a separate thread.

Fields Summary
protected ProblemSet
currProblem
protected OutputStream
clientOut
protected InputStream
clientIn
Constructors Summary
public RunnableSolver(InputStream cin, OutputStream cout)

   // Source of problems

  // Constructors
       
    super();
    clientIn = cin;
    clientOut = cout;
  
Methods Summary
public voidPrintResults(java.io.OutputStream os)

    PrintStream pos = new PrintStream(os);
    pos.println("Problem solution: " + currProblem.getSolution());
  
public intgetIterations()

    // Not used on this solver
    return 0;
  
public ProblemSetgetProblem()

    return currProblem;
  
public voidrun()

    solve();
  
public voidsetIterations(int dummy)

    // Not used on this solver
  
public voidsetProblem(ProblemSet s)

    currProblem = s;
  
public booleansolve()

    boolean success = true;
    SimpleCmdInputStream sin = new SimpleCmdInputStream(clientIn);
    String inStr = null;
    try {
      System.out.println("Reading from client...");
      inStr = sin.readString();
    }
    catch (IOException e) {
      System.out.println("Error reading data from client.");
      return false;
    }

    if (inStr.compareTo("problem") == 0) {
      try {
        inStr = sin.readString();
      }
      catch (IOException e) {
        System.out.println("Error reading data from client.");
        return false;
      }

      System.out.println("Got \"" + inStr + "\" from client.");
      double problem = Double.valueOf(inStr).doubleValue();
      ProblemSet p = new ProblemSet();
      p.setValue(problem);
      success = solve(p, 0);
    }
    else {
      System.out.println("Error reading problem from client.");
      return false;
    }

    return success;
  
public booleansolve(ProblemSet s, int iters)

    boolean success = true;

    if (s == null) {
      System.out.println("No problem to solve.");
      return false;
    }

    System.out.println("Problem value = " + s.getValue());

    // Solve problem here...
    try {
      s.setSolution(Math.sqrt(s.getValue()));
    }
    catch (ArithmeticException e) {
      System.out.println("Badly-formed problem.");
      success = false;
    }

    System.out.println("Problem solution = " + s.getSolution());
    System.out.println("Sending solution to output...");

    // Write the solution to the designated output destination
    try {
      DataOutputStream dout = new DataOutputStream(clientOut);
      dout.writeChars("solution=" + s.getSolution() + "\n");
    }
    catch (IOException e) {
      System.out.println("Error writing results to output.");
      success = false;
    }

    return success;