Esempio n. 1
0
  public static GeneTable getGeneTable(GeneSet gs) {
    if (instance != null && instance.gs.equals(gs)) {
      return instance;
    }
    final Semaphore sem = new Semaphore(1);
    try {
      sem.acquire();
      GeneFetcher gf =
          new GeneFetcher(gs, "GeneFetcher") {
            @Override
            public void setData(Object[][] data) {
              instance = new GeneTable(data);
              sem.release();
            }

            @Override
            public void showProgress(double prog) {}
          };

      gf.execute();

      sem.acquire();
    } catch (Exception ex) {
      LOG.error(ex);
    }
    return instance;
  }
Esempio n. 2
0
 public static void main(String args[]) {
   Semaphore s = new Semaphore(5);
   NumberServer n = new NumberServer();
   ExecutorService executorService = Executors.newFixedThreadPool(10);
   List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
   for (int i = 0; i < 10; i++) {
     try {
       s.acquire();
     } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     executorService.execute(
         new Runnable() {
           public void run() {
             list.add(n.getNumber());
             s.release();
           }
         });
   }
   executorService.shutdown();
   try {
     s.acquire(5);
   } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   for (int i = 0; i < 10; i++) {
     System.out.println(list.get(i));
   }
 }
Esempio n. 3
0
  public String lock(ZooKeeper zk) {
    try {
      if (zk.exists(LOCK_NAME, null) == null) {
        System.err.println("+ Attempt to create lock node, if not exists");
        zk.create(LOCK_NAME, new byte[16], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
      }

      // Create new child
      String nodeName =
          zk.create(
              LOCK_NAME + "/" + LOCK_PREFIX,
              new byte[16],
              Ids.OPEN_ACL_UNSAFE,
              CreateMode.EPHEMERAL_SEQUENTIAL);
      Integer nodeNumber = extractNodeNumber(nodeName);
      local_lock.acquire();

      while (true) {
        List<String> children = zk.getChildren(LOCK_NAME, this);
        if (isNumberMinimal(children, nodeNumber)) {
          System.err.println("- Got a lock: " + nodeName);
          return nodeName;
        }
        local_lock.acquire();
      }

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 4
0
  public void createVisionWorld() {
    final Semaphore semaphore = new Semaphore(1);

    try {
      semaphore.acquire();
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }

    /*
     * TODO: restore visionworld integration here AbstractSensorMatrixDialog
     * dialog = new AbstractSensorMatrixDialog() { private static final long
     * serialVersionUID = 1L;
     *
     * @Override protected PixelMatrix getPixelMatrix() { return image;// =
     * new BufferedImagePixelMatrix(agent.getSnapshot()); }
     *
     * @Override protected void ok(SensorMatrix sensorMatrix) { matrix =
     * sensorMatrix; VisionWorldModel model = new
     * MutableVisionWorldModel(image, matrix); VisionWorldComponent
     * component = new VisionWorldComponent(getName() + " vision", model);
     *
     * components.add(new WeakReference<VisionWorldComponent>(component));
     *
     * workspace.addWorkspaceComponent(component); semaphore.release(); } };
     *
     * dialog.init(); dialog.setBounds(100, 100, 450, 550);
     * dialog.setVisible(true);
     */
    try {
      semaphore.acquire();
    } catch (InterruptedException e) {

    }
  }
Esempio n. 5
0
  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();
  }
Esempio n. 6
0
 private void goToCouch() {
   if (personGui.isInBedroom()) {
     personGui.DoGoToWall();
     try {
       isMoving.acquire();
     } catch (InterruptedException e) {
       //   Auto-generated catch block
       e.printStackTrace();
     }
   }
   personGui.DoGoToCouch();
   try {
     isMoving.acquire();
   } catch (InterruptedException e) {
     //   Auto-generated catch block
     e.printStackTrace();
   }
   timer.schedule(
       new TimerTask() {
         public void run() {
           homeState = HomeState.none;
         }
       },
       3000);
 }
Esempio n. 7
0
  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();
  }
  public void pushSRI(StreamSRI header) {

    if (logger != null) {
      logger.trace("bulkio.InPort pushSRI  ENTER (port=" + name + ")");
    }
    synchronized (sriUpdateLock) {
      if (!currentHs.containsKey(header.streamID)) {
        if (logger != null) {
          logger.debug("pushSRI PORT:" + name + " NEW SRI:" + header.streamID);
        }
        if (sriCallback != null) {
          sriCallback.newSRI(header);
        }
        currentHs.put(header.streamID, new sriState(header, true));
        if (header.blocking) {
          // If switching to blocking we have to set the semaphore
          synchronized (dataBufferLock) {
            if (!blocking) {
              try {
                queueSem.acquire(workQueue.size());
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
            }
            blocking = true;
          }
        }
      } else {
        StreamSRI oldSri = currentHs.get(header.streamID).getSRI();
        boolean cval = false;
        if (sri_cmp != null) {
          cval = sri_cmp.compare(header, oldSri);
        }
        if (cval == false) {
          if (sriCallback != null) {
            sriCallback.changedSRI(header);
          }
          this.currentHs.put(header.streamID, new sriState(header, true));
          if (header.blocking) {
            // If switching to blocking we have to set the semaphore
            synchronized (dataBufferLock) {
              if (!blocking) {
                try {
                  queueSem.acquire(workQueue.size());
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
              }
              blocking = true;
            }
          }
        }
      }
    }
    if (logger != null) {
      logger.trace("bulkio.InPort pushSRI  EXIT (port=" + name + ")");
    }
  }
Esempio n. 9
0
  @Test(timeout = 30000)
  public void testAsyncMapperReducer() throws Exception {

    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);

    HazelcastInstance h1 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h2 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h3 = nodeFactory.newHazelcastInstance();

    IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME);
    for (int i = 0; i < 100; i++) {
      m1.put(i, i);
    }

    final Map<String, Integer> listenerResults = new HashMap<String, Integer>();
    final Semaphore semaphore = new Semaphore(1);
    semaphore.acquire();

    JobTracker tracker = h1.getJobTracker("default");
    Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
    ICompletableFuture<Map<String, Integer>> future =
        job.mapper(new GroupingTestMapper())
            .reducer(new TestReducerFactory()) //
            .submit();

    future.andThen(
        new ExecutionCallback<Map<String, Integer>>() {
          @Override
          public void onResponse(Map<String, Integer> response) {
            try {
              listenerResults.putAll(response);
            } finally {
              semaphore.release();
            }
          }

          @Override
          public void onFailure(Throwable t) {
            semaphore.release();
          }
        });

    // Precalculate results
    int[] expectedResults = new int[4];
    for (int i = 0; i < 100; i++) {
      int index = i % 4;
      expectedResults[index] += i;
    }

    semaphore.acquire();

    for (int i = 0; i < 4; i++) {
      assertEquals(expectedResults[i], (int) listenerResults.get(String.valueOf(i)));
    }
  }
Esempio n. 10
0
  /** Thread for simulation */
  @Override
  public void run() {
    final ArrayList<PhysicBody> bodies = mOnSceneBodies;
    long lastTime = System.currentTimeMillis();
    long time;
    final Vector2D force = new Vector2D();

    for (; !mDoKill; ) {
      try {
        mSimulationMutex.acquire();
      } catch (InterruptedException e2) {
        e2.printStackTrace();
      }

      /* Compute time */
      time = System.currentTimeMillis() - lastTime;
      lastTime = System.currentTimeMillis();

      /* We need a semaphore here */
      try {
        mLockOnSceneBodys.acquire();
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }
      /* Apply gravity impulse */
      for (PhysicBody body : bodies) {
        force.set(mGravity);
        body.applyImpulse(force.mul(body.getBodyMass() * (float) time / 1000f));
      }
      mLockOnSceneBodys.release();

      /* Then apply collisions forces */
      mArbiter.checkCollisions();

      try {
        mLockOnSceneBodys.acquire();
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }
      /* Last update body */
      for (PhysicBody body : bodies) body.onUpdateBody((float) time / 1000f);

      mLockOnSceneBodys.release();

      mSimulationMutex.release();
      /* Keep max frame-rate */
      try {
        if (time < 40) Thread.sleep(40 - time);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    mDoKill = false;
  }
Esempio n. 11
0
  public Foo2() {
    sem1 = new Semaphore(1);
    sem2 = new Semaphore(1);

    try {
      sem1.acquire();
      sem2.acquire();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Esempio n. 12
0
  @Test(timeout = 30000)
  public void testAsyncMapperReducerCollator() throws Exception {

    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);

    HazelcastInstance h1 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h2 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h3 = nodeFactory.newHazelcastInstance();

    IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME);
    for (int i = 0; i < 100; i++) {
      m1.put(i, i);
    }

    final int[] result = new int[1];
    final Semaphore semaphore = new Semaphore(1);
    semaphore.acquire();

    JobTracker tracker = h1.getJobTracker("default");
    Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
    ICompletableFuture<Integer> future =
        job.mapper(new GroupingTestMapper())
            .reducer(new TestReducerFactory())
            .submit(new TestCollator());

    future.andThen(
        new ExecutionCallback<Integer>() {
          @Override
          public void onResponse(Integer response) {
            try {
              result[0] = response.intValue();
            } finally {
              semaphore.release();
            }
          }

          @Override
          public void onFailure(Throwable t) {
            semaphore.release();
          }
        });

    // Precalculate result
    int expectedResult = 0;
    for (int i = 0; i < 100; i++) {
      expectedResult += i;
    }

    semaphore.acquire();

    for (int i = 0; i < 4; i++) {
      assertEquals(expectedResult, result[0]);
    }
  }
Esempio n. 13
0
  private void makeFood() {
    hungerLevel = 0;
    for (String key : inventory.keySet()) {
      if (inventory.get(key) > 0) {
        inventory.put(key, inventory.get(key) - 1);
        break;
      }
    }
    if (personGui.isInBedroom()) {
      personGui.DoAlmostWall();
      try {
        isMoving.acquire();
      } catch (InterruptedException e) {

        e.printStackTrace();
      }
      personGui.DoGoToWall();
      try {
        isMoving.acquire();
      } catch (InterruptedException e) {
        //
        e.printStackTrace();
      }
    }
    personGui.DoGoToRefridgerator();
    try {
      isMoving.acquire();
    } catch (InterruptedException e) {
      //   Auto-generated catch block
      e.printStackTrace();
    }
    personGui.DoGoToStove();
    try {
      isMoving.acquire();
    } catch (InterruptedException e) {
      //   Auto-generated catch block
      e.printStackTrace();
    }
    timer.schedule(
        new TimerTask() {
          public void run() {
            homeState = HomeState.onCouch;
            isMoving.release();
          }
        },
        5000);
    try {
      isMoving.acquire();
    } catch (InterruptedException e) {
      //   Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 14
0
 protected void leaveHome() {
   currentBuilding = cityData.buildings.get(home.buildingNumber);
   if (personGui.isInBedroom()) {
     personGui.DoAlmostWall();
     try {
       isMoving.acquire();
     } catch (InterruptedException e) {
       //   Auto-generated catch block
       e.printStackTrace();
     }
     personGui.DoGoToWall();
     try {
       isMoving.acquire();
     } catch (InterruptedException e) {
       //   Auto-generated catch block
       e.printStackTrace();
     }
   }
   if (home instanceof Home) {
     personGui.DoGoToEntrance();
     atEntrance.drainPermits();
     try {
       atEntrance.acquire();
     } catch (InterruptedException e) {
       //   Auto-generated catch block
       e.printStackTrace();
     }
     personGui.DoLeaveBuilding();
     currentBuilding.LeaveBuilding(this);
   }
   if (home instanceof Apartment) {
     Apartment a = (Apartment) home;
     personGui.DoGoToEntrance();
     try {
       isMoving.acquire();
     } catch (InterruptedException e1) {
       //   Auto-generated catch block
       e1.printStackTrace();
     }
     a.rooms.get(roomNumber).LeaveBuilding(this);
     personGui.DoGoToHallway();
     try {
       isMoving.acquire();
     } catch (InterruptedException e) {
       //   Auto-generated catch block
       e.printStackTrace();
     }
     personGui.DoLeaveBuilding();
     a.LeaveBuilding(this);
   }
   bigState = BigState.doingNothing;
 }
Esempio n. 15
0
 public void getCliente() throws InterruptedException {
   mutex.acquire();
   if (numClientiInAttesa == 0) {
     barbiereAddormentato = true;
     mutex.release();
     barbiere.acquire();
     barbiereAddormentato = false;
   } else {
     clienteInAttesa.release();
     barbiere.acquire();
   }
   mutex.release();
 }
Esempio n. 16
0
  protected void goToBusStop(int destinationBusStopNumber, Point location) {

    print("Going to bus Stop " + gui.getClosestBusStopNumber());
    gui.doGoToBusStop();
    // Finish the GUI version of it
    try {
      atCityDestination.acquire();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    print("At bus Stop " + gui.getClosestBusStopNumber() + ". Now waiting");
    Phonebook.getPhonebook()
        .getAllBusStops()
        .get(gui.getClosestBusStopNumber())
        .waitingForBus(this);
    try {
      waitingAtBus.acquire();
      // waitingAtBus.acquire();
      // maybe have to do double acquires?
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    print(
        "Telling "
            + Phonebook.getPhonebook()
                .getAllBusStops()
                .get(gui.getClosestBusStopNumber())
                .getCurrentBus()
                .getName()
            + " that I'm getting on to go to bus stop # "
            + destinationBusStopNumber);
    Phonebook.getPhonebook()
        .getAllBusStops()
        .get(gui.getClosestBusStopNumber())
        .getCurrentBus()
        .msgGettingOnBus(this, destinationBusStopNumber);
    gui.setInvisible();
    try {
      beingTransported.acquire();
      // beingTransported.acquire();
      // maybe have to do double acquires?
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    print("Arriving at destination Bus Stop: " + destinationBusStopNumber);
    gui.getOffBus(destinationBusStopNumber);
    gui.setxDestination(location.x);
    gui.setyDestination(location.y);
  }
Esempio n. 17
0
 /**
  * After getting to the intermediate position, sends the teller to the right station. After he
  * gets there, sends a message to the number announcer enabling him to increment the announcer.
  */
 private void goToStation() {
   try {
     atIntermediate.acquire();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   doGoToStation();
   try {
     atStation.acquire();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   announcer.msgAddBankTeller(this);
   announcer.msgTransactionComplete(LineNum, this, null);
 }
Esempio n. 18
0
      @Override
      public void run() {
        try {
          startLatch.await();
          for (int j = 0; j < numberOfIds; j++) {
            for (int k = 0; k < numberOfUpdatesPerId; ++k) {
              updateRequestsOutstanding.acquire();
              UpdateRequest ur =
                  client()
                      .prepareUpdate("test", "type1", Integer.toString(j))
                      .setScript("ctx._source.field += 1", ScriptService.ScriptType.INLINE)
                      .setRetryOnConflict(retryOnConflict)
                      .setUpsert(jsonBuilder().startObject().field("field", 1).endObject())
                      .setListenerThreaded(false)
                      .request();
              client().update(ur, new UpdateListener(j));

              deleteRequestsOutstanding.acquire();
              DeleteRequest dr =
                  client()
                      .prepareDelete("test", "type1", Integer.toString(j))
                      .setListenerThreaded(false)
                      .setOperationThreaded(false)
                      .request();
              client().delete(dr, new DeleteListener(j));
            }
          }
        } catch (Throwable e) {
          logger.error("Something went wrong", e);
          failures.add(e);
        } finally {
          try {
            waitForOutstandingRequests(
                TimeValue.timeValueSeconds(60),
                updateRequestsOutstanding,
                maxUpdateRequests,
                "Update");
            waitForOutstandingRequests(
                TimeValue.timeValueSeconds(60),
                deleteRequestsOutstanding,
                maxDeleteRequests,
                "Delete");
          } catch (ElasticsearchTimeoutException ete) {
            failures.add(ete);
          }
          latch.countDown();
        }
      }
  private void processNewGrid(DataBean bean) {
    final Integer[] gridDims = (Integer[]) bean.getGuiParameters().get(GuiParameters.IMAGEGRIDSIZE);

    if (gridDims != null && gridDims.length > 0) {
      try {
        locker.acquire();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      canvas
          .getDisplay()
          .asyncExec(
              new Runnable() {
                @Override
                public void run() {
                  imageGrid.dispose();
                  if (gridDims.length == 1)
                    imageGrid =
                        new PlotServerSWTImageGrid(gridDims[0], gridDims[0], canvas, plotViewName);
                  else
                    imageGrid =
                        new PlotServerSWTImageGrid(gridDims[1], gridDims[0], canvas, plotViewName);
                  imageGrid.setThumbnailSize(getPreferenceImageSize());
                  locker.release();
                  canvas.redraw();
                }
              });
    }
    cleanUpOnServer();
  }
  /**
   * This method defines what an Customer does: The customer attempts to enter the restaurant (only
   * successful when the restaurant has a free table), place its order, and then leave the
   * restaurant when the order is complete.
   */
  public void run() {

    Simulation.logEvent(SimulationEvent.customerStarting(this));
    try {

      tableSpace.acquire();

      Simulation.logEvent(SimulationEvent.customerEnteredCoffeeShop(this));

      Simulation.logEvent(SimulationEvent.customerPlacedOrder(this, this.order, this.orderNum));

      Simulation.orders.put(new FoodOrder(this.orderNum, this.order, this));

      while (Simulation.custMap.get(this) == false) {
        Thread.sleep(15);
      }

      Simulation.logEvent(SimulationEvent.customerReceivedOrder(this, this.order, this.orderNum));

      Simulation.logEvent(SimulationEvent.customerLeavingCoffeeShop(this));

      tableSpace.release();

    } catch (InterruptedException e) {

    }
  }
Esempio n. 21
0
  /** {@inheritDoc} */
  @Override
  public void close(final CameraSession session) {
    final Session s = (Session) session;

    try {
      lock.acquire();

      if (s.captureSession != null) {
        closeLatch = new CountDownLatch(1);
        s.captureSession.close();
        closeLatch.await(2, TimeUnit.SECONDS);
        s.captureSession = null;
      }

      if (s.cameraDevice != null) {
        s.cameraDevice.close();
        s.cameraDevice = null;
      }

      if (s.reader != null) {
        s.reader.close();
      }

      Descriptor camera = (Descriptor) session.getDescriptor();

      camera.setDevice(null);
      getBus().post(new ClosedEvent());
    } catch (Exception e) {
      getBus().post(new ClosedEvent(e));
    } finally {
      lock.release();
    }
  }
  private boolean enterRoom(String roomName) {
    final Semaphore semaphore = new Semaphore(1);
    try {
      semaphore.acquire();
    } catch (Exception e) {
    }
    ;
    baseActivity.runOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            fab.performClick();
            semaphore.release();
          }
        });
    /*
    getInstrumentation().runOnMainSync(new Runnable() {
        @Override
        public void run() {
            LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View input_dialog = inflater.inflate(R.layout.input_dialog, null);
            textInputLayout = (TextInputLayout) input_dialog.findViewById(R.id.textInput);
            editText = textInputLayout.getEditText();
            editText.requestFocus();
        }
    });*/
    getInstrumentation().waitForIdleSync();
    getInstrumentation().sendStringSync(roomName);
    getInstrumentation().waitForIdleSync();

    assertNotNull("Text Input Layout  is not null", textInputLayout);
    assertNotNull("Edit Text is not null", editText);
    semaphore.release();

    try {
      Thread.sleep(1000);
    } catch (Exception e) {
    }
    ;
    Instrumentation.ActivityMonitor activityMonitor =
        getInstrumentation().addMonitor(QuestionRoomFragment.class.getName(), null, false);

    try {
      Thread.sleep(1000);
    } catch (Exception e) {
    }
    ;
    // QuestionRoomFragment questionFragment = (QuestionRoomFragment)
    // getInstrumentation().waitForMonitorWithTimeout(activityMonitor,2000);
    try {
      Thread.sleep(1000);
    } catch (Exception e) {
    }
    ;
    /*
    boolean result = (questionFragment != null);
    if(result)
        questionFragment.finish();*/
    return true;
  }
 public void cancelPingKeepAliveTimeoutTaskIfStarted() {
   if (pingKeepAliveTimeoutTask != null && pingKeepAliveTimeoutTask.getSipTimerTask() != null) {
     try {
       keepAliveSemaphore.acquire();
     } catch (InterruptedException e) {
       logger.logError("Couldn't acquire keepAliveSemaphore");
       return;
     }
     try {
       if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
         logger.logDebug(
             "~~~ cancelPingKeepAliveTimeoutTaskIfStarted for MessageChannel(key="
                 + key
                 + "), clientAddress="
                 + peerAddress
                 + ", clientPort="
                 + peerPort
                 + ", timeout="
                 + keepAliveTimeout
                 + ")");
       }
       sipStack.getTimer().cancel(pingKeepAliveTimeoutTask);
     } finally {
       keepAliveSemaphore.release();
     }
   }
 }
    public void waitForClients() {
      try {
        clientsSemaphore.acquire();
      } catch (InterruptedException ex) {

      }
    }
Esempio n. 25
0
  private void waitForBlockStored(Sha256Hash hash) {
    if (hash.toString().equals("0000000000000000000000000000000000000000000000000000000000000000"))
      return;

    try {
      if (file_db.getBlockMap().containsKey(hash)) return;
    } finally {

    }

    Semaphore block_wait_sem = null;
    synchronized (in_progress) {
      block_wait_sem = in_progress.get(hash);
      if (block_wait_sem == null) {
        block_wait_sem = new Semaphore(0);
        in_progress.put(hash, block_wait_sem);
      }
    }

    try {
      // System.out.println("Waiting for " + hash);
      block_wait_sem.acquire(1);

    } catch (java.lang.InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 26
0
 /**
  * Start the application
  *
  * @throws IOException if there is a problem with connection
  * @throws InterruptedException if thread was interrupted
  */
 private void start() throws IOException, InterruptedException {
   Connection c = new Connection(myHost.getHostName(), myHost.getPort());
   try {
     configureKnownHosts(c);
     c.connect(new HostKeyVerifier());
     authenticate(c);
     final Session s = c.openSession();
     try {
       s.execCommand(myCommand);
       // Note that stdin is not being waited using semaphore.
       // Instead, the SSH process waits for remote process exit
       // if remote process exited, none is interested in stdin
       // anyway.
       forward("stdin", s.getStdin(), System.in, false);
       forward("stdout", System.out, s.getStdout(), true);
       forward("stderr", System.err, s.getStderr(), true);
       myForwardCompleted.acquire(2); // wait only for stderr and stdout
       s.waitForCondition(ChannelCondition.EXIT_STATUS, Long.MAX_VALUE);
       Integer exitStatus = s.getExitStatus();
       if (exitStatus == null) {
         // broken exit status
         exitStatus = 1;
       }
       System.exit(exitStatus.intValue() == 0 ? myExitCode : exitStatus.intValue());
     } finally {
       s.close();
     }
   } finally {
     c.close();
   }
 }
Esempio n. 27
0
  public void mouseEntered() {
    try {
      loadedMutex.acquire();
      if (rootCrowdLoaded) {
        Point mousePosition = new Point(MouseInfo.getPointerInfo().getLocation());
        SwingUtilities.convertPointFromScreen(mousePosition, this);

        for (int i = 0; i < rootCrowd.getMouseActionList().size(); i++) {
          // if the mouse click is in the hitbox then peform the action
          if (rootCrowd.getMouseActionList().get(i).isActive()
              && rootCrowd
                  .getMouseActionList()
                  .get(i)
                  .isInBounds(mousePosition.x, mousePosition.y)) {
            rootCrowd.getMouseActionList().get(i).mI(mousePosition);
          } else if (rootCrowd.getMouseActionList().get(i).isActive()
              && !rootCrowd
                  .getMouseActionList()
                  .get(i)
                  .isInBounds(mousePosition.x, mousePosition.y)) {
            rootCrowd.getMouseActionList().get(i).mO(mousePosition);
          }
        }
      }
      loadedMutex.release();
    } catch (InterruptedException ie) {
      System.err.println("interrupedMouseEnter");
      Thread.currentThread().interrupt();
    }
  }
Esempio n. 28
0
 /** Locks the screen */
 private void getLock_Screen() {
   try {
     mLockScreen.acquire(); // Gets the semaphore
   } catch (InterruptedException ie) {
     System.out.println("ScreenLogger thread interrupted while waiting for the semaphore");
   }
 }
  private void processNewFile(DataBean bean) {
    try {
      locker.acquire();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    playback.addFile((String) bean.getGuiParameters().get(GuiParameters.FILENAME));
    String colourScheme = getPreferenceColourMapChoice();

    SWTGridEntry entry =
        new SWTGridEntry(
            (String) bean.getGuiParameters().get(GuiParameters.FILENAME),
            bean.getData().get(0),
            canvas,
            colourScheme,
            getPreferenceAutoContrastLo(),
            getPreferenceAutoContrastHi());
    Integer xPos = (Integer) bean.getGuiParameters().get(GuiParameters.IMAGEGRIDXPOS);
    Integer yPos = (Integer) bean.getGuiParameters().get(GuiParameters.IMAGEGRIDYPOS);
    if (xPos != null && yPos != null) imageGrid.addEntry(entry, xPos, yPos);
    else imageGrid.addEntry(entry);
    imageGrid.setThumbnailSize(getPreferenceImageSize());
    locker.release();
    if (liveActive) playback.moveToLast();
  }
Esempio n. 30
0
  @NotNull
  public ASTNode parse(IElementType root, PsiBuilder builder) {
    if (ALLOW_ONLY_ONE_THREAD) {
      try {
        SEMAPHORE.acquire();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    // builder.setDebugMode(true);
    final PsiBuilder.Marker rootMarker = builder.mark();
    if (!builder.eof()) { // Empty file is not an error
      final GLSLParsing theRealParser = new GLSLParsing(builder);

      theRealParser.parseTranslationUnit();
      while (!builder.eof()) // exhaust the file if unable to parse everything
      builder.advanceLexer();
    }

    rootMarker.done(root);

    if (ALLOW_ONLY_ONE_THREAD) {
      SEMAPHORE.release();
    }
    return builder.getTreeBuilt();
  }