Ejemplo n.º 1
0
  /// The watcher thread - from the Runnable interface.
  // This has to be pretty anal to avoid monitor lockup, lost
  // threads, etc.
  public synchronized void run() {
    Thread me = Thread.currentThread();
    me.setPriority(Thread.MAX_PRIORITY);

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    startTimeInNs = threadMXBean.getCurrentThreadCpuTime();

    if (enabled.get()) {
      do {
        loop.set(false);
        try {
          wait(millis);
        } catch (InterruptedException e) {
        }
      } while (enabled.get() && loop.get());
    }

    if (enabled.get() && targetThread.isAlive()) {
      isDoneRunning.set(true);

      printThread();
      if (kill) {
        logger.warn(
            "Trying to kill thread with id:"
                + targetThread.getId()
                + " but did not as it can cause deadlocks etc.");
        // targetThread.interrupt();
        // targetThread.stop(); //Never kill thread - it can cause other problems
      }
      done();
      isDoneRunning.set(false);
    }
  }
Ejemplo n.º 2
0
  private void startListening() {
    // if listener thread is alive and listening now, no need to recreate. Just reuse it.
    if (listenerThread != null && listenerThread.isAlive()) {
      return;
    }

    Runnable listeningAction =
        () -> {
          boolean running = true;
          while (connected && running) {
            List<String> list = getMessages();

            localHistory.addAll(list);

            try {
              Thread.sleep(POLLING_PERIOD_MILLIS);
            } catch (InterruptedException e) {
              logger.error("The message listening thread was interrupted", e);
              running = false;
            }
          }
        };
    listenerThread = new Thread(listeningAction);
    listenerThread.start();
  }
Ejemplo n.º 3
0
  /** Stops unicast and multicast receiver threads */
  void stopThreads() {
    Thread tmp;

    // 1. Stop the multicast receiver thread
    if (mcast_receiver != null) {
      if (mcast_receiver.isAlive()) {
        tmp = mcast_receiver;
        mcast_receiver = null;
        closeMulticastSocket(); // will cause the multicast thread to terminate
        tmp.interrupt();
        try {
          tmp.join(100);
        } catch (Exception e) {
        }
        tmp = null;
      }
      mcast_receiver = null;
    }

    // 2. Stop the unicast receiver thread
    if (ucast_receiver != null) {
      ucast_receiver.stop();
      ucast_receiver = null;
    }

    // 3. Stop the in_packet_handler thread
    if (incoming_packet_handler != null) {
      incoming_packet_handler.stop();
    }
  }
Ejemplo n.º 4
0
  public void start(ContentHandler sax, Target target) throws IOException, SAXException {
    this.target = target;

    XMLReader parser;
    try {
      parser = spf.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException e) {
      throw new LagoonException(e.getMessage());
    }

    parser.setContentHandler(sax);
    parser.setEntityResolver(
        new EntityResolver() {
          public InputSource resolveEntity(String publicId, String systemId)
              throws SAXException, IOException {
            InputSource is = new InputSource(getSourceMan().getFileURL(systemId));

            File fil = getSourceMan().getFile(systemId);

            if (fil != null) {
              InputStream istr = new FileInputStream(fil);
              is.setByteStream(istr);
            }

            return is;
          }
        });

    exception = null;

    mis = new MyInputStream();
    mos = new MyOutputStream(mis);

    thread = new Thread(this);
    thread.start();

    parser.parse(new InputSource(mis));
    mis.close();

    try {
      thread.join(1000);
    } catch (InterruptedException e) {
    }

    if (thread.isAlive()) {
      thread.interrupt();
    }

    this.target = null;

    if (exception != null) {
      if (exception instanceof SAXException) {
        throw (SAXException) exception;
      } else if (exception instanceof IOException) {
        throw (IOException) exception;
      }
    }
  }
Ejemplo n.º 5
0
 synchronized void start() {
   if (queue.closed()) queue.reset();
   if (thread == null || !thread.isAlive()) {
     thread = getThreadFactory().newThread(this, "ViewHandler");
     thread.setDaemon(
         false); // thread cannot terminate if we have tasks left, e.g. when we as coord leave
     thread.start();
   }
 }
Ejemplo n.º 6
0
 public void start() {
   if (streamReader != null && streamReader.isAlive()) {
     System.out.println("Camera already started");
     return;
   }
   streamReader = new Thread(this, "HTTP Stream reader");
   keepAlive = true;
   streamReader.start();
 }
Ejemplo n.º 7
0
  public void stop() {
    Util.close(srv_sock);

    if (acceptor != null && acceptor.isAlive()) acceptor.interrupt();

    Util.sleep(500);
    if (!sockets.isEmpty()) {
      for (Socket sock : sockets) Util.close(sock);
    }
  }
Ejemplo n.º 8
0
 public synchronized void handle(Socket socket) throws IOException {
   con = new Connection(socket);
   count = 0;
   if (thread == null || !thread.isAlive()) {
     thread = new Thread(runners, this);
     thread.start();
   } else {
     notify();
   }
 }
Ejemplo n.º 9
0
 public void stop() {
   Thread tmp;
   if (thread != null && thread.isAlive()) {
     running = false;
     tmp = thread;
     thread = null;
     closeSocket(); // this will cause the thread to break out of its loop
     tmp.interrupt();
     tmp = null;
   }
   thread = null;
 }
Ejemplo n.º 10
0
 public void stop() {
   if (streamReader == null || !streamReader.isAlive()) {
     System.out.println("Camera already stopped");
     return;
   }
   keepAlive = false;
   try {
     streamReader.join();
   } catch (InterruptedException e) {
     System.err.println(e.getMessage());
   }
 }
Ejemplo n.º 11
0
  public static void startChat(Socket socket) {

    InputStream input;
    DataInputStream dis = null;
    OutputStream output;
    DataOutputStream dos = null;

    try {
      input = socket.getInputStream();
      dis = new DataInputStream(input);
      output = socket.getOutputStream();
      dos = new DataOutputStream(output);

      dos.writeInt(3); // send 5 as request to server to request for chat
    } catch (IOException e) {
      System.out.println("Cannot send requests to server.");
    }

    System.out.println("Enter your message and hit enter to send.\n");

    connectedToChat = true;

    Thread readThread = new Thread(new Read(dis));
    Thread writeThread = new Thread(new Write(dos));
    readThread.start();
    writeThread.start();

    while ((writeThread.isAlive()) && (readThread.isAlive())) {}

    System.out.println("Disconnected from chat. Enter anything to return to menu.");

    if (!writeThread.isAlive()) {
      Scanner scanner = new Scanner(System.in);
      scanner.next();
    }

    while (writeThread.isAlive()) {}
  }
 public boolean runMacroTool(String name) {
   for (int i = 0; i < nMacros; i++) {
     if (macroNames[i].startsWith(name)) {
       if (macroToolThread != null
           && macroToolThread.getName().indexOf(name) != -1
           && macroToolThread.isAlive())
         return false; // do nothing if this tool is already running
       MacroRunner mw = new MacroRunner(pgm, macroStarts[i], name, (String) null);
       macroToolThread = mw.getThread();
       // IJ.log("runMacroTool: "+macroToolThread);
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 13
0
  private void startMessageSending() {
    // if listener thread is alive and listening now, no need to recreate. Just reuse it.
    if (messageSendingThread != null && messageSendingThread.isAlive()) {
      return;
    }

    Runnable messageSendingAction =
        () -> {
          Scanner scanner = new Scanner(System.in);
          while (connected) {
            String message = scanner.nextLine();
            sendMessage(message);
          }
        };
    messageSendingThread = new Thread(messageSendingAction);
    messageSendingThread.start();
  }
Ejemplo n.º 14
0
  private synchronized String getLinuxDMIInfo(String dmiType, String target) {
    // only try to get dmidecode information once, after that, we can
    // reuse the output
    if (dmiInfo == null) {
      Thread dmidecodeThread =
          new Thread() {
            public void run() {
              dmiInfo = getCommandOutput("/usr/sbin/dmidecode");
            }
          };
      dmidecodeThread.start();

      try {
        dmidecodeThread.join(2000);
        if (dmidecodeThread.isAlive()) {
          dmidecodeThread.interrupt();
          dmiInfo = "";
        }
      } catch (InterruptedException ie) {
        dmidecodeThread.interrupt();
      }
    }

    if (dmiInfo.length() == 0) {
      return "";
    }
    boolean dmiFlag = false;
    for (String s : dmiInfo.split("\n")) {
      String line = s.toLowerCase();
      if (dmiFlag) {
        if (line.contains(target)) {
          String key = target + ":";
          int indx = line.indexOf(key) + key.length();
          if (line.contains(key) && indx < line.length()) {
            return line.substring(indx).trim();
          }
          String[] ss = line.split(":");
          return ss[ss.length - 1];
        }
      } else if (line.contains(dmiType)) {
        dmiFlag = true;
      }
    }
    return "";
  }
 /** compareAndSet in one thread enables another waiting for value to succeed */
 public void testCompareAndSetInMultipleThreads() {
   final AtomicLong ai = new AtomicLong(1);
   Thread t =
       new Thread(
           new Runnable() {
             public void run() {
               while (!ai.compareAndSet(2, 3)) Thread.yield();
             }
           });
   try {
     t.start();
     assertTrue(ai.compareAndSet(1, 2));
     t.join(LONG_DELAY_MS);
     assertFalse(t.isAlive());
     assertEquals(ai.get(), 3);
   } catch (Exception e) {
     unexpectedException();
   }
 }
  private void startBackgroundThread() {
    if (updateAllInBackground == null || !updateAllInBackground.isAlive()) {
      updateAllInBackground =
          new Thread("UpdateAllThread") {

            @Override
            public void run() {
              while (!isInterrupted()) {
                try {
                  sleep(settings.getAutoupdateInterval() * 1000);
                  updateAll();
                } catch (InterruptedException ex) {
                  return;
                }
              }
            }
          };
      updateAllInBackground.start();
    }
  }
Ejemplo n.º 17
0
  /** Starts the unicast and multicast receiver threads */
  void startThreads() throws Exception {
    if (ucast_receiver == null) {
      // start the listener thread of the ucast_recv_sock
      ucast_receiver = new UcastReceiver();
      ucast_receiver.start();
      if (Trace.trace) {
        Trace.info("UDP.startThreads()", "created unicast receiver thread");
      }
    }

    if (ip_mcast) {
      if (mcast_receiver != null) {
        if (mcast_receiver.isAlive()) {
          if (Trace.trace) {
            Trace.info(
                "UDP.createThreads()",
                "did not create new multicastreceiver thread as existing "
                    + "multicast receiver thread is still running");
          }
        } else {
          mcast_receiver = null; // will be created just below...
        }
      }

      if (mcast_receiver == null) {
        mcast_receiver = new Thread(this, "UDP mcast receiver");
        mcast_receiver.setPriority(Thread.MAX_PRIORITY); // needed ????
        mcast_receiver.setDaemon(true);
        mcast_receiver.start();
      }
    }
    if (use_outgoing_packet_handler) {
      outgoing_packet_handler.start();
    }
    if (use_incoming_packet_handler) {
      incoming_packet_handler.start();
    }
  }
Ejemplo n.º 18
0
 private void runCpu() {
   if (cpuThread != null && cpuThread.isAlive()) return;
   runButton.setEnabled(false);
   execButton.setEnabled(false);
   stepButton.setEnabled(false);
   pauseButton.setEnabled(true);
   cpuThread =
       new Thread(
           new Runnable() {
             public void run() {
               debugger.run();
               // on halt
               runButton.setEnabled(true);
               execButton.setEnabled(true);
               stepButton.setEnabled(true);
               pauseButton.setEnabled(false);
               registersModel.fireUpdate();
               memoryModel.fireUpdate(0, RAM_SIZE - 1); // TODO optimize
             }
           },
           "CpuThread");
   cpuThread.setDaemon(true);
   cpuThread.start();
 }
Ejemplo n.º 19
0
 public boolean isAlive() {
   return streamReader.isAlive();
 }
Ejemplo n.º 20
0
 /**
  * Returns true if the server is ready to accept new clients.
  *
  * @return true if the server is listening.
  */
 public final boolean isListening() {
   return connectionListener != null && connectionListener.isAlive(); // modified in version 2.31
 }
Ejemplo n.º 21
0
 public final boolean isAlive() {
   return wasStarted() && !myServerSocket.isClosed() && myThread.isAlive();
 }
Ejemplo n.º 22
0
 public boolean isAlive() {
   return thread.isAlive();
 }
Ejemplo n.º 23
0
  /**
   * Try to update an old block to a new block. If there are ongoing create threads running for the
   * old block, the threads will be returned without updating the block.
   *
   * @return ongoing create threads if there is any. Otherwise, return null.
   */
  private synchronized List<Thread> tryUpdateBlock(Block oldblock, Block newblock)
      throws IOException {
    // check ongoing create threads
    final ActiveFile activefile = ongoingCreates.get(oldblock);
    if (activefile != null && !activefile.threads.isEmpty()) {
      // remove dead threads
      for (Iterator<Thread> i = activefile.threads.iterator(); i.hasNext(); ) {
        final Thread t = i.next();
        if (!t.isAlive()) {
          i.remove();
        }
      }

      // return living threads
      if (!activefile.threads.isEmpty()) {
        return new ArrayList<Thread>(activefile.threads);
      }
    }

    // No ongoing create threads is alive. Update block.
    File blockFile = findBlockFile(oldblock.getBlockId());
    if (blockFile == null) {
      throw new IOException("Block " + oldblock + " does not exist.");
    }

    File oldMetaFile = findMetaFile(blockFile);
    long oldgs = parseGenerationStamp(blockFile, oldMetaFile);

    // rename meta file to a tmp file
    File tmpMetaFile =
        new File(
            oldMetaFile.getParent(),
            oldMetaFile.getName() + "_tmp" + newblock.getGenerationStamp());
    if (!oldMetaFile.renameTo(tmpMetaFile)) {
      throw new IOException("Cannot rename block meta file to " + tmpMetaFile);
    }

    // update generation stamp
    if (oldgs > newblock.getGenerationStamp()) {
      throw new IOException(
          "Cannot update block (id="
              + newblock.getBlockId()
              + ") generation stamp from "
              + oldgs
              + " to "
              + newblock.getGenerationStamp());
    }

    // update length
    if (newblock.getNumBytes() > oldblock.getNumBytes()) {
      throw new IOException(
          "Cannot update block file (="
              + blockFile
              + ") length from "
              + oldblock.getNumBytes()
              + " to "
              + newblock.getNumBytes());
    }
    if (newblock.getNumBytes() < oldblock.getNumBytes()) {
      truncateBlock(blockFile, tmpMetaFile, oldblock.getNumBytes(), newblock.getNumBytes());
    }

    // rename the tmp file to the new meta file (with new generation stamp)
    File newMetaFile = getMetaFile(blockFile, newblock);
    if (!tmpMetaFile.renameTo(newMetaFile)) {
      throw new IOException("Cannot rename tmp meta file to " + newMetaFile);
    }

    updateBlockMap(ongoingCreates, oldblock, newblock);
    updateBlockMap(volumeMap, oldblock, newblock);

    // paranoia! verify that the contents of the stored block
    // matches the block file on disk.
    validateBlockMetadata(newblock);
    return null;
  }
 private void checkTransferThread() {
   if (transferThread != null && transferThread.isAlive() || isDone()) {
     throw new IllegalStateException("File transfer in progress or has already completed.");
   }
 }
Ejemplo n.º 25
0
 public void stop() {
   if (relaxer.isAlive()) {
     relaxer.stop();
   }
   relaxer = null;
 }
Ejemplo n.º 26
0
  public static void testMiddleware() {
    rdfStream = new ByteArrayOutputStream();
    Thread rdfThread =
        new Thread() {
          public void run() {
            File buildFile = new File("../rdfUtils/build.xml");
            Project project = new Project();
            project.setUserProperty("ant.file", buildFile.getAbsolutePath());
            PrintStream ps = new PrintStream(rdfStream);

            try {
              project.fireBuildStarted();
              DefaultLogger consoleLogger = new DefaultLogger();
              consoleLogger.setErrorPrintStream(System.err);
              consoleLogger.setOutputPrintStream(ps);
              consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
              project.addBuildListener(consoleLogger);

              project.init();
              ProjectHelper projectHelper = ProjectHelper.getProjectHelper();
              project.addReference("ant.projectHelper", projectHelper);
              projectHelper.parse(project, buildFile);
              project.executeTarget("run-rdfTest-nointeract");
              project.fireBuildFinished(null);
            } catch (Exception e) {
              System.out.println(e);
            }
          }
        };

    rdfThread.start();

    System.out.println("RDF Module should be running, starting tests..");
    try {
      long endTime = testStartTime + maxTestRunDuration;
      System.out.println("Started at " + testStartTime + " and running until " + endTime);
      while ((endTime > System.currentTimeMillis()) && rdfThread.isAlive()) {
        if (rdfStream.size() > 0) {
          String latestString = rdfStream.toString("UTF8");
          System.out.println(latestString);
          if (latestString.contains("TestRDF Rate")) {
            String[] splited = latestString.split("\\s+");
            RDFSent = Integer.parseInt(splited[8]);
            RDFRec = Integer.parseInt(splited[11]);
            System.out.println("RDF sent " + RDFSent + " and rec " + RDFRec);
            if (RDFSent > 1000) {
              // System.out.println("RDF min send/rec rate test passed");
              RDFCheck = true;
            }
          } else if (latestString.contains("TestRDF Loss")) {
            String[] splited = latestString.split("\\s+");
            RDFLossSent = Integer.parseInt(splited[7]);
            RDFLossRec = Integer.parseInt(splited[10]);
            System.out.println("RDFLoss sent " + RDFLossSent + " and rec " + RDFLossRec);
            rdfLossResult = splited[12];
            System.out.println("overall loss result " + rdfLossResult);
            if (rdfLossResult.equals("OK")) {
              RDFLossCheck = true;
              // System.out.println("RDF packet loss test passed");
            }
          }
          rdfStream.reset();
        }
      }

      System.out.println("ending test" + endS);
      if (rdfThread.isAlive()) {
        rdfThread.interrupt();
      }
    } catch (Exception e) {
      System.out.println(e);
    }

    try {
      if (RDFCheck) {
        testResults.write(
            "<testcase classname=\"RDF\" name=\"Sent\" status=\"" + RDFSent + "\"/>" + endS);
        testResults.write(
            "<testcase classname=\"RDF\" name=\"Received\" status=\"" + RDFRec + "\"/>" + endS);
      } else {
        testResults.write("<testcase classname=\"RDF\" name=\"Sent\">" + endS);
        testResults.write(
            "  <failure type=\"Middleware Performanace, sent\"> " + RDFSent + " </failure>" + endS);
        testResults.write("</testcase>" + endS);
        testResults.write("<testcase classname=\"RDF\" name=\"Received\">" + endS);
        testResults.write(
            "  <failure type=\"Middleware Performanace, received\"> "
                + RDFRec
                + " </failure>"
                + endS);
        testResults.write("</testcase>" + endS);
      }

      if (RDFLossCheck) {
        testResults.write(
            "<testcase classname=\"RDF\" name=\"Loss\" status=\""
                + (RDFLossSent - RDFLossRec)
                + "\"/>"
                + endS);
      } else {
        testResults.write("<testcase classname=\"RDF\" name=\"Loss\">" + endS);
        testResults.write(
            "  <failure type=\"Message loss \"> "
                + (RDFLossSent - RDFLossRec)
                + " </failure>"
                + endS);
        testResults.write("</testcase>" + endS);
      }
    } catch (Exception e) {
      System.out.println("error writing to file");
    }
  }
Ejemplo n.º 27
0
  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()
  }