Example #1
0
  /**
   * This method is the main function of the thread of the collective. It does housekeeping and
   * regularly talks to peers to exchange information. It can be stopped by calling <code>close()
   * </code>.
   *
   * @see #close()
   */
  public final void run() {

    while (shouldLive) {
      // try{
      System.gc();
      removeOldStuff();
      if (!refresh()) {
        Address[] a = observer.getPeerAddresses();
        if (a != null)
          synchronized (cache) {
            for (int i = 0; i < a.length; ++i)
              cache.put(a[i].name, new ContributionBox(a[i], null));
          }
      }
      for (int i = 0; i < REFRESHRATE; i += 1000) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          shouldLive = false;
        }
        if (shouldLive == false) break;
        Thread.yield();
      }
      /*}
      catch( RuntimeException e )
      {
      	Logger.error( "Collective#run()",
      	"Runtime exception caught, something is going wrong",e);

      }*/
    }

    cache = null;
    observer = null;
  }
Example #2
0
  /**
   * The run method for the thread that retrieves the data from the database. This method should not
   * be called directly. Instead use the retrieve method.
   */
  public void run() {
    try {
      DataStoreRow row = new DataStoreRow(this, new DSDataRow(_desc), _desc);

      while (_dataSource.retrieveRow(this, row)) {
        _rows.addElement(row.getDSDataRow());
        if (_threaded) notifyListeners(ModelChangedEvent.TYPE_ROW_INSERTED_OR_DELETED);

        if (!_retrieveInProgress || (_maxRows > -1 && _rows.size() >= _maxRows)) {
          _cancelInProgress = true;
          _retrieveInProgress = false;
          interruptWaitingRetrieveThreads();
          break;
        }
        if (_threaded) Thread.yield();

        row.setDSDataRow(new DSDataRow(_desc));
      }
      _dataSource.postRetrieve(this);
      _cancelInProgress = false;
      interruptWaitingCancelThreads();
      notifyListeners(ModelChangedEvent.TYPE_DATA_LOADED);
    } catch (Exception e) {
      System.out.println("DataStore.run:" + e);
      _cancelInProgress = false;
      interruptWaitingCancelThreads();
    }

    _retrieveInProgress = false;
    interruptWaitingRetrieveThreads();
    _cancelInProgress = false;
    interruptWaitingCancelThreads();
  }
Example #3
0
 public static void spinAssertEquals(Object expected, Supplier<Object> s, int timeoutInSeconds) {
   long now = System.currentTimeMillis();
   while (System.currentTimeMillis() - now < now + (1000 * timeoutInSeconds)) {
     if (s.get().equals(expected)) break;
     Thread.yield();
   }
   assertEquals(expected, s.get());
 }
 @Test
 public void canEcho() throws Exception {
   server.start();
   Thread.yield();
   Socket s = new Socket("localhost", port);
   OutputStream os = s.getOutputStream();
   os.write("echo\n".getBytes());
   String response = new BufferedReader(new InputStreamReader(s.getInputStream())).readLine();
   assertEquals("echo", response);
 }
  public void run() {
    boolean eof = false;
    JavaCharStream stream = new JavaCharStream(in, 1, 1);

    exec("_ps1 = sys.ps1");
    PyObject ps1Obj = get("_ps1");
    String ps1 = ps1Obj.toString();

    exec("_ps2 = sys.ps2");
    PyObject ps2Obj = get("_ps2");
    String ps2 = ps2Obj.toString();
    out.print(getDefaultBanner() + "\n");

    out.print(ps1);
    String line = "";

    while (!eof) {
      // try to sync up the console
      System.out.flush();
      System.err.flush();
      Thread.yield(); // this helps a little

      try {
        boolean eol = false;
        line = "";

        while (!eol) {
          char aChar = stream.readChar();
          eol = (aChar == '\n');
          if (!eol) line = line + aChar;
        }

        // hitting Enter at prompt returns a semicolon
        // get rid of it since it returns an error when executed
        if (line.equals(";")) line = "";

        {
          boolean retVal = push(line);

          if (retVal) {
            out.print(ps2);
          } else {
            out.print(ps1);
          }
        }
      } catch (IOException ex) {
      }
    }
  }
Example #6
0
  public static boolean kill() {
    int j = 0;
    Thread meMySelfI = Thread.currentThread();

    do {
      /* iter across the thread group, killing all members. */
      shutdown = true;
      Thread list[] = new Thread[tg.activeCount()];

      // get all members of the group (including submembers)
      int i = tg.enumerate(list);

      // no members means that we have gracefully suceeded
      if (i == 0) return true;

      // if some of the threads do IO during the shut down they will
      // need time to accomplish the IO. So, I give it to 'em
      // after the first attempt.
      if (j > 0)
        try {
          meMySelfI.sleep(500);
        } catch (Exception e) {
        }
      ;

      // try to shudown each thread in the group
      while (i-- > 0) {
        FlickrFtpd tftp = (FlickrFtpd) list[i];
        tftp.interrupt(); // first, do it politely
        meMySelfI.yield(); // give 'em time to respond
        tftp.forceClose(); // second, use a big hammer
        meMySelfI.yield(); // give 'em time to respond
      }
    } while (j++ <= 3);
    return false;
  }
  @Test
  public void multipleEchos() throws Exception {
    server.start();
    Thread.yield();

    Socket s1 = new Socket("localhost", port);
    Socket s2 = new Socket("localhost", port);

    s1.getOutputStream().write("echo1\n".getBytes());
    s2.getOutputStream().write("echo2\n".getBytes());

    String response1 = new BufferedReader(new InputStreamReader(s1.getInputStream())).readLine();
    String response2 = new BufferedReader(new InputStreamReader(s2.getInputStream())).readLine();

    assertEquals("echo1", response1);
    assertEquals("echo2", response2);
  }
Example #8
0
 /**
  * Returns the current file cache.
  *
  * @param root root directory
  * @return id, or {@code null} if newer file cache exists
  * @throws InterruptedException interruption
  */
 ProjectCache cache(final IOFile root) throws InterruptedException {
   final ProjectCache pc = cache;
   if (pc == null) {
     // no file cache available: create and return new one
     cache = new ProjectCache();
     add(root, cache);
     cache.finish();
   } else {
     // wait until file cache is initialized
     while (!pc.valid()) {
       Thread.yield();
       // file cache was replaced with newer version
       if (pc != cache) throw new InterruptedException();
     }
   }
   // return existing file cache
   return cache;
 }
Example #9
0
 static void doIt(String toParse, BufferedWriter fw, SimpleNode optNode) throws Exception {
   long[] testArray = new long[10];
   double d = 0;
   DoubleStack stack = new DoubleStack();
   for (int j = 0; j < 10; j++) {
     Thread.yield();
     long start = System.currentTimeMillis();
     for (int i = 0; i < 100000; i++) {
       d = optNode.getValue();
     }
     testArray[j] = System.currentTimeMillis() - start;
   }
   fw.write("100000 evaluations: ");
   for (int j = 0; j < 10; j++) {
     fw.write(testArray[j] + ", ");
   }
   fw.write("\n");
 }
  protected BTGPSLocationProvider() throws LocationException {

    // TODO: Move this to searchConnect method?
    // TODO: The problem here is that it searches every time. Slow. Need to try Properties?
    // TODO: BIG ONE: Should only connect to GPS that isPaired() (from menu). Will
    // allow some degree of control over which GPS is connects to in classroom.
    try {
      da = LocalDevice.getLocalDevice().getDiscoveryAgent();
      da.startInquiry(DiscoveryAgent.GIAC, this);
    } catch (BluetoothStateException e) {
      throw new LocationException(e.getMessage());
    }

    while (!doneInq) {
      Thread.yield();
    }

    if (btDevice == null) throw new LocationException("No device found");

    String address = btDevice.getBluetoothAddress();
    String btaddy = "btspp://" + address;

    try {
      StreamConnectionNotifier scn = (StreamConnectionNotifier) Connector.open(btaddy);

      if (scn == null) throw new LocationException("Bad BT address");
      StreamConnection c = scn.acceptAndOpen();

      /* This problem below occurred one time for my Holux GPS. The solution was to
       * remove the device from the Bluetooth menu, then find and pair again.
       */
      if (c == null) throw new LocationException("Failed. Try pairing at menu again");
      InputStream in = c.openInputStream();

      if (in != null) {
        gps = new SimpleGPS(in);
        // c.close(); // TODO: Clean up when done. HOW TO HANDLE IN LOCATION?
      }
    } catch (IOException e) {
      throw new LocationException(e.getMessage());
    }
    // Add itself to SimpleGPS as listener
    SimpleGPS.addListener(this);
  }
Example #11
0
  /**
   * This one checks that the stats message was received. If not, the message is sent again up to
   * five times. Run time an best individual of run are logged.
   */
  public void finalStatistics(final EvolutionState state, final int result) {
    super.finalStatistics(state, result);

    EvolutionAgent agent = (EvolutionAgent) state;

    StatisticsData data =
        new StatisticsData(
            new Address(agent.getName()),
            state.generation,
            System.currentTimeMillis() - creationtime,
            getBestIndividual(state),
            getBestIndividual(state));

    if (agent.iamroot) // Local logging
    printStatistics(state, data); // Every statistic will go there
    else { // DRM logging
      for (int i = 0; i < 5; i++) { // Try to send final data 5 times
        IRequest request = agent.fireMessage(agent.getRootAddress(), EvolutionAgent.M_STATS, data);
        while (request.getStatus() == IRequest.WAITING) {
          Thread.yield();
          // try{Thread.sleep(1000);}
          // catch(Exception e){state.output.error("Exception: " + e);}
        }
        if (request.getStatus() == IRequest.DONE) {
          break;
        } else {
          state.output.error("There was an error sending final statistics.");
          try {
            Thread.sleep(1000 * i ^ 2);
          } catch (Exception e) {
            state.output.error("Exception: " + e);
          }
        }
      }
    }
  }
Example #12
0
    public void run() {
      if (cnt == 0) {
        // Give precedence to the Thread that is creating the BackEnd
        Thread.yield();

        // In the meanwhile load the ConnectionListener if any
        try {
          myConnectionListener =
              (ConnectionListener)
                  Class.forName(props.getProperty("connection-listener")).newInstance();
        } catch (Exception e) {
          // Just ignore it
        }
      }
      myId = cnt++;
      myLogger.log(Logger.INFO, "IM-" + myId + " started");

      // Prepare an initial dummy response
      JICPPacket rsp = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, null);
      while (active) {
        try {
          // Prepare the connection for next incoming command
          refreshConnection();

          myDisconnectionManager.waitUntilReachable();
          // Deliver the response to the previous incoming command and wait for the next one
          // If we are delivering the response to an exit command, set active to false to avoid an
          // annoying stack trace
          // (due to the fact that the back-end will close the connection instead of sending further
          // commands) and exit
          if (this == terminator) {
            active = false;
          }
          JICPPacket cmd = deliver(rsp, myConnection);
          myKeepAliveManager.update();
          if (cmd.getType() == JICPProtocol.KEEP_ALIVE_TYPE) {
            // Keep-alive
            if (myLogger.isLoggable(Logger.FINER)) {
              myLogger.log(Logger.FINER, "Keep-alive received");
            }
            rsp = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.OK_INFO, null);
          } else {
            // Command
            byte sid = cmd.getSessionID();
            if (sid == lastSid) {
              myLogger.log(Logger.WARNING, "Duplicated command received " + sid);
              rsp = lastResponse;
            } else {
              myLogger.log(Logger.FINE, "Incoming command received " + sid);
              byte[] rspData = mySkel.handleCommand(cmd.getData());
              myLogger.log(Logger.FINE, "Incoming command served " + sid);
              rsp = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, rspData);
              rsp.setSessionID(sid);
              lastSid = sid;
              lastResponse = rsp;
            }
          }
        } catch (Exception e) {
          if (active) {
            myLogger.log(Logger.WARNING, "Exception on input connection", e);
            // Note that the boolean value passed to setUnreachable() only indicates if the
            // unreachability was detected by a missing keep-alive
            myDisconnectionManager.setUnreachable(false);
          }
        }
      }
      myLogger.log(Logger.INFO, "IM-" + myId + " terminated");
    }
Example #13
0
  public static void main(String[] args) throws Exception {
    Date startTime = new Date();
    parseParams(args);
    File inFile = new File((String) params.get("-file"));
    File logFile = new File((String) params.get("-logfile"));

    BufferedReader fr = new BufferedReader(new FileReader(inFile));
    BufferedWriter fw = new BufferedWriter(new FileWriter(logFile));

    jep.addStandardConstants();
    jep.addStandardFunctions();

    String curLine = null;
    int lines = 0;
    while (null != (curLine = fr.readLine())) {
      if (curLine.startsWith("#")) continue;
      String description = curLine;
      String toParse = fr.readLine();
      double result = Double.parseDouble(fr.readLine().trim());

      fw.write("Processing:" + toParse + ",\n");
      fw.write("Expected: " + result + "\n");
      fw.flush();

      // Give enought time to the jit compiler.
      double d = 0;
      DoubleStack stack = new DoubleStack();
      for (int i = 0; i < 1000; i++) {
        jep.parseExpression(toParse);
        d = jep.getValue(stack);
      }
      SimpleNode optNode = jep.getTopNode();
      // if(Boolean.getBoolean("noopt")) {
      fw.write("Not Optimized: ");
      doIt(toParse, fw, optNode);
      // }

      // if(Boolean.getBoolean("opt")) {
      ExpressionOptimizer optimizer = new ExpressionOptimizer(jep.getTopNode());
      // optimizer.addConst("pi");
      // optimizer.addConst("e");
      optNode = optimizer.optimize();

      fw.write("Optimized    : ");

      doIt(toParse, fw, optNode);

      long[] testArray = new long[10];
      for (int j = 0; j < 10; j++) {
        Thread.yield();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
          jep.parseExpression(toParse);
        }
        testArray[j] = System.currentTimeMillis() - start;
      }
      fw.write("1000 parses: ");
      for (int j = 0; j < 10; j++) {
        fw.write(testArray[j] + ", ");
      }
      fw.write("\n");
      fw.write(d + "\n_____________________________________________________\n");
      fw.flush();
      // }
    }
    Date endTime = new Date();
    fw.write("Start time: " + startTime + "\n");
    fw.write("End time: " + endTime + "\n");
    fw.write("Total time: " + (endTime.getTime() - startTime.getTime()) + " ms");
    fw.close();
  }
  public void setLocationListener(
      LocationListener listener, int interval, int timeout, int maxAge) {

    // * Stop all previous listener threads *
    listenerRunning = false;
    if (listyThread != null) {
      while (listyThread.isAlive()) {
        Thread.yield();
      } // End old thread
      listyThread = null; // Discard the listener thread instance
    }

    // * Remove any listeners from GPSListener *
    if (listener == null) {
      // Remove current listener from SimpleGPS
      SimpleGPS.removeListener(gpsl);
      gpsl = null;
      return; // No listener provided, so return now so it dosn't make a new one
    }

    // * Inner classes need final variables *
    final int to = timeout;
    final LocationListener l = listener;
    final LocationProvider lp = this;
    final int delay = interval * 1000; // Oddly interval is in seconds, and not float

    // Make new thread here and start it if interval > 0, else if -1
    // then use the GPSListener interface.
    if (interval > 0) { // Notify according to interval by user
      listyThread =
          new Thread() {
            public void run() {
              while (listenerRunning) {
                try {
                  // TODO: Probably only notify if location changed? Need to compare to old.
                  // TODO: Make helper method since this is used below too.
                  l.locationUpdated(lp, lp.getLocation(to));
                  Thread.sleep(delay);
                } catch (LocationException e) {
                  // TODO Auto-generated catch block
                } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                }
              }
            }
          };
      listyThread.setDaemon(true); // so JVM exits if thread is still running
      listenerRunning = true;
      listyThread.start();
    } else if (interval < 0) { // If interval is -1, use default update interval
      // In our case, update as soon as new coordinates are available from GPS (via GPSListener)
      // TODO: Alternate method: Use GPSListener for ProximityListener and this.
      gpsl =
          new GPSListener() {
            public void sentenceReceived(NMEASentence sen) {
              // Check if GGASentence. Means that new location info is ready
              if (sen.getHeader().equals(GGASentence.HEADER)) {
                try {
                  // TODO: Probably only notify if location changed? Need to compare to old.
                  l.locationUpdated(lp, lp.getLocation(to));
                } catch (LocationException e) {
                  // TODO Auto-generated catch block
                } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                }
              }
            }
          };
      SimpleGPS.addListener(gpsl);
    }

    // TODO: Need to implement LocationListener.providerStateChanged()
  }