コード例 #1
0
ファイル: Buffer.java プロジェクト: darkxemis/Procesos
  public void producir(Thread thr) throws InterruptedException {

    lleno.acquire();
    mutex.acquire();

    buffer[entrada] = 1;
    System.out.println("Hebraproductora: " + thr.getName() + " produce en posición: " + entrada);
    Productorconsumidor.mostrar.setText(
        Productorconsumidor.mostrar.getText() + "Productor produce " + "\n");
    entrada = (entrada + 1) % buffer.length;
    contador = contador + 1;

    System.out.println("Productor produce ");
    for (int i = 0; i < buffer.length; i++) {
      System.out.print("[" + buffer[i] + "]");
    }

    for (int i = 0; i < buffer.length; i++) {
      Productorconsumidor.mostrar.setText(
          Productorconsumidor.mostrar.getText() + "[" + buffer[i] + "]");
    }
    Productorconsumidor.mostrar.setText(Productorconsumidor.mostrar.getText() + "\n");
    System.out.print("\n");

    mutex.release();
    vacio.release();
  }
コード例 #2
0
ファイル: Buffer.java プロジェクト: darkxemis/Procesos
  public void consumir(Thread thr) throws InterruptedException {

    vacio.acquire();
    mutex.acquire();

    buffer[salida] = 0;
    System.out.println("Hebraconsumidora: " + thr.getName() + " consume en posición: " + salida);
    Productorconsumidor.mostrar.setText(
        Productorconsumidor.mostrar.getText() + "Productor consume " + "\n");
    salida = (salida + 1) % buffer.length;
    contador = contador - 1;
    System.out.println("Consumidor consume ");
    for (int i = 0; i < buffer.length; i++) {
      System.out.print("[" + buffer[i] + "]");
    }

    for (int i = 0; i < buffer.length; i++) {
      Productorconsumidor.mostrar.setText(
          Productorconsumidor.mostrar.getText() + "[" + buffer[i] + "]");
    }
    Productorconsumidor.mostrar.setText(Productorconsumidor.mostrar.getText() + "\n");
    System.out.print("\n");

    mutex.release();
    lleno.release();
  }
コード例 #3
0
  /**
   * Asynchronously runs the Proton {@link Reactor} accepting and sending messages. Any other call
   * to this method on this {@link AmqpsIotHubConnection} will block until the {@link Reactor}
   * terminates and this {@link AmqpsIotHubConnection} closes. Normally, this method should only be
   * called once by the {@link #open()} method until the {@link AmqpsIotHubConnection} has been
   * closed.
   *
   * @throws IOException if the {@link AmqpsIotHubConnectionBaseHandler} has not been initialized.
   * @throws InterruptedException if there is a problem acquiring the semaphore.
   */
  private synchronized void startReactorAsync() throws IOException, InterruptedException {
    // Acquire permit to continue execution of this method and spawn a new thread.
    reactorSemaphore.acquire();

    if (this.amqpsHandler != null) {
      this.reactor = Proton.reactor(this);

      new Thread(
              () -> {
                try {
                  reactor.run();

                  // Closing here should be okay. The reactor will only stop running if the
                  // connection is remotely
                  // or locally closed. The transport will attempt to receive/send a message and
                  // will get an exception
                  // causing it to create a new AmqpsIoTHubConnection.
                  close();

                  // Release the semaphore and make permit available allowing for the next reactor
                  // thread to spawn.
                  reactorSemaphore.release();
                } catch (Exception e) {
                  close();
                  reactorSemaphore.release();
                }
              })
          .start();
    } else {
      throw new IOException(
          "The Handler has not been initialized. Ensure that the AmqpsIotHubConnection is in an OPEN state by calling open().");
    }
  }
コード例 #4
0
 public void getReady() {
   try {
     ready.acquire();
     ready.release();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
コード例 #5
0
 public void submitTask(final Runnable command) throws InterruptedException {
   semaphore.acquire();
   try {
     exec.execute(
         new Runnable() {
           public void run() {
             try {
               command.run();
             } finally {
               semaphore.release();
             }
           }
         });
   } catch (RejectedExecutionException e) {
     semaphore.release();
   }
 }
コード例 #6
0
  public void put(Object x) throws InterruptedException {

    /*
      Basic protocol is:
      1. Wait until a taker arrives (via unclaimedTakers_ semaphore)
      2. Wait until no other puts are active (via onePut_)
      3. Insert the item, and signal taker that it is ready
         (via itemAvailable_ semaphore).
      4. Wait for item to be taken (via itemTaken_ semaphore).
      5. Allow another put to insert item (by releasing onePut_).

      Backouts due to interrupts or (for offer) timeouts are allowed
      only during the wait for takers. Upon claiming a taker, puts
      are forced to proceed, ignoring interrupts.
    */

    unclaimedTakers_.acquire();
    doPut(x);
  }
コード例 #7
0
  protected void doPut(Object x) {
    synchronized (onePut_) {
      insert(x);
      itemAvailable_.release();

      // Must ignore interrupts while waiting for acknowledgement
      boolean wasInterrupted = false;

      for (; ; ) {
        try {
          itemTaken_.acquire();
          break;
        } catch (InterruptedException ex) {
          wasInterrupted = true;
        }
      }

      if (wasInterrupted) Thread.currentThread().interrupt();
    }
  }
コード例 #8
0
ファイル: Rendezvous.java プロジェクト: huluwa/z_zdal
  protected Object doRendezvous(Object x, boolean timed, long msecs)
      throws InterruptedException, TimeoutException, BrokenBarrierException {

    // rely on semaphore to throw interrupt on entry

    long startTime;

    if (timed) {
      startTime = System.currentTimeMillis();
      if (!entryGate_.attempt(msecs)) {
        throw new TimeoutException(msecs);
      }
    } else {
      startTime = 0;
      entryGate_.acquire();
    }

    synchronized (this) {
      Object y = null;

      int index = entries_++;
      slots_[index] = x;

      try {
        // last one in runs function and releases
        if (entries_ == parties_) {

          departures_ = entries_;
          notifyAll();

          try {
            if (!broken_ && rendezvousFunction_ != null)
              rendezvousFunction_.rendezvousFunction(slots_);
          } catch (RuntimeException ex) {
            broken_ = true;
          }

        } else {

          while (!broken_ && departures_ < 1) {
            long timeLeft = 0;
            if (timed) {
              timeLeft = msecs - (System.currentTimeMillis() - startTime);
              if (timeLeft <= 0) {
                broken_ = true;
                departures_ = entries_;
                notifyAll();
                throw new TimeoutException(msecs);
              }
            }

            try {
              wait(timeLeft);
            } catch (InterruptedException ex) {
              if (broken_ || departures_ > 0) { // interrupted after release
                Thread.currentThread().interrupt();
                break;
              } else {
                broken_ = true;
                departures_ = entries_;
                notifyAll();
                throw ex;
              }
            }
          }
        }

      } finally {

        y = slots_[index];

        // Last one out cleans up and allows next set of threads in
        if (--departures_ <= 0) {
          for (int i = 0; i < slots_.length; ++i) slots_[i] = null;
          entryGate_.release(entries_);
          entries_ = 0;
        }
      }

      // continue if no IE/TO throw
      if (broken_) throw new BrokenBarrierException(index);
      else return y;
    }
  }
コード例 #9
0
  protected Object doTake(boolean timed, long msecs) throws InterruptedException {

    /*
      Basic protocol is:
      1. Announce that a taker has arrived (via unclaimedTakers_ semaphore),
          so that a put can proceed.
      2. Wait until the item is put (via itemAvailable_ semaphore).
      3. Take the item, and signal the put (via itemTaken_ semaphore).

      Backouts due to interrupts or timeouts are allowed
      only during the wait for the item to be available. However,
      even here, if the put of an item we should get has already
      begun, we ignore the interrupt/timeout and proceed.

    */

    // Holds exceptions caught at times we cannot yet rethrow or reinterrupt
    InterruptedException interruption = null;

    // Records that a timeout or interrupt occurred while waiting for item
    boolean failed = false;

    // Announce that a taker is present
    unclaimedTakers_.release();

    // Wait for a put to insert an item.

    try {
      if (!timed) itemAvailable_.acquire();
      else if (!itemAvailable_.attempt(msecs)) failed = true;
    } catch (InterruptedException ex) {
      interruption = ex;
      failed = true;
    }

    //  Messy failure mechanics

    if (failed) {

      // On interrupt or timeout, loop until either we can back out or acquire.
      // One of these must succeed, although it may take
      // multiple tries due to re-interrupts

      for (; ; ) {

        // Contortion needed to avoid catching our own throw
        boolean backout = false;

        try {
          // try to deny that we ever arrived.
          backout = unclaimedTakers_.attempt(0);

          // Cannot back out because a put is active.
          // So retry the acquire.

          if (!backout && itemAvailable_.attempt(0)) break;
        } catch (InterruptedException e) {
          if (interruption == null) // keep first one if a re-interrupt
          interruption = e;
        }

        if (backout) {
          if (interruption != null) throw interruption;
          else // must have been timeout
          return null;
        }
      }
    }

    // At this point, there is surely an item waiting for us.
    // Take it, and signal the put

    Object x = extract();
    itemTaken_.release();

    // if we had to continue even though interrupted, reset status
    if (interruption != null) Thread.currentThread().interrupt();

    return x;
  }
コード例 #10
0
  @SuppressWarnings("unchecked")
  public void test() {
    try {
      confRuns.setFileName("confRuns.xml");
      confDbs.setFileName("confDbs.xml");
      confDatasources.setFileName("confDatasources.xml");
      confMethods.setFileName("confMethods.xml");

      confRuns.load();
      confDbs.load();
      confDatasources.load();
      confMethods.load();

      List<String> runs = confRuns.getList("run");
      log.info("Start of testing");
      // runs = new TestRun[confRuns.getInt("threads")];
      int numRuns = confRuns.getInt("threads");
      String resultsFile = "";
      semRuns = new Semaphore(numRuns);
      // Iterate through runs
      for (String run : runs) {
        int dbId = 0;
        run = "runs." + run;
        // Iterate through dbs
        while (confRuns.getProperty(run + ".dbs.db(" + dbId + ").name") != null) {
          String dbName = confRuns.getString(run + ".dbs.db(" + dbId + ").name");
          List<String> datasources = confRuns.getList(run + ".dbs.db(" + dbId + ").datasources");
          int datasourceId = 0;
          // Iterate through datasources
          for (String datasourceName : datasources) {
            int methodId = 0;
            // Iterate through methods
            while (confRuns.getProperty(run + ".methods.method(" + methodId + ").name") != null) {
              String methodName =
                  confRuns.getString(run + ".methods.method(" + methodId + ").name");
              int testId = 0;
              // Iterate through tests
              while (confRuns.getProperty(run + ".tests.test(" + testId + ").class") != null) {
                synchronized (semRuns) {
                  // Waiting for a free slot;
                  semRuns.acquire();

                  String testClass = confRuns.getString(run + ".tests.test(" + testId + ").class");
                  Constructor[] a = Class.forName(testClass).getConstructors();
                  log.info("Datasource " + datasourceName + ", method " + methodName);
                  System.gc();
                  BasicDataSource trainDataSource = getDataSource(datasourceName, dbName);
                  trainDataSource.configDriver(confRuns, run + ".dbs.db(" + dbId + ")");
                  trainDataSource.configDataSource(
                      confRuns, run + ".dbs.db(" + dbId + ").datasources(" + datasourceId + ")");
                  BasicDataSource testDataSource = getDataSource(datasourceName, dbName);
                  testDataSource.configDriver(confRuns, run + ".dbs.db(" + dbId + ")");
                  testDataSource.configDataSource(
                      confRuns, run + ".dbs.db(" + dbId + ").datasources(" + datasourceId + ")");

                  // ExportAsTHSource.exportAsTHSource(trainDataSource, "C:\\data\\",
                  // trainDataSource.getName());
                  // writeRecords(trainDataSource);
                  // writeRecords(testDataSource);
                  // DataSourceStatistics b = new DataSourceStatistics(trainDataSource.getName());
                  // b.getStatistics(trainDataSource);
                  // semRuns.release();
                  InductiveMethod method = getMethod(methodName);
                  method.configClassifier(confRuns, run + ".methods.method(" + methodId + ")");

                  Test test = (Test) a[0].newInstance();
                  test.configTest(confRuns, run + ".tests.test(" + testId + ")");
                  resultsFile = test.getResultsInterpreter().getFilePrefix() + ".csv";

                  log.info("Testing datasource " + trainDataSource.getName());
                  // Making new thread for a new test.
                  new TestRun(this, trainDataSource, testDataSource, method, test).start();
                  // Wait 1 second for avoid of the colision
                  // in writing of results.
                  Thread.sleep(1000);
                }
                testId++;
              }
              methodId++;
            }
            datasourceId++;
          }
          dbId++;
        }
      }
      // Waiting for all other threads to finish.
      for (int i = 0; i < numRuns; i++) semRuns.acquire();

      log.info("End of testing");

      Process p = Runtime.getRuntime().exec("cmd ", null, null);
      p.getOutputStream().write(("loadResults.bat " + resultsFile + "\n").getBytes());
      p.getOutputStream().flush();
      p.getOutputStream().write("exit\n".getBytes());
      p.getOutputStream().flush();
      BufferedReader stdOut = new BufferedReader(new InputStreamReader(p.getInputStream()));
      BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      while (true) {
        try {
          p.exitValue();
          break;
        } catch (Exception e) {
          while (stdOut.ready() || stdErr.ready()) {
            if (stdOut.ready()) stdOut.readLine();
            else stdErr.readLine();
          }
        }
      }
      p.waitFor();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }