@Override protected void doJob() throws Exception { // log.debug("doJob()"); temperatureBufferBlockMap.allocate(); boolean localHalt = shouldHalt; while (!localHalt) { try { jobsToDoSemaphore.acquire(); jobsToDoSemaphore.drainPermits(); if (SampleCache.DEBUG_SAMPLE_CACHE_ACTIVITY) { log.trace("Attempting to refresh cache."); } sampleCache.refreshCache(); } catch (final InterruptedException ie) { // Don't care, probably woken up to shutdown } catch (final Exception e) { if (log.isErrorEnabled()) { log.error("Exception caught during cache population run: " + e.toString(), e); } } localHalt = shouldHalt; } }
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)); } }
/** * Clear all consumed data for the given process id from this data pipeline. * * @param id The process id. * @return The map of output data which has been stored for the given process id until now. */ @Override public Map<String, Object> clear(Long id) { Semaphore resultSemaphoreForProcess = resultSemaphores.remove(id); Map<String, Object> result = pendingOutputs.remove(id); resultSemaphoreForProcess.release(); return result; }
/** * 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) { } }
public static void waitUntilBlock(int threadCount) { Semaphore semaphore = _semaphore; if (semaphore != null) { while (semaphore.getQueueLength() < threadCount) ; } }
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 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(); }
private void scheduleReconnect() { /* * Ensure you are the only one mucking with connections If you find someone * else is doing so, then you don't get a turn We trust this other person to * do the needful */ if (lock.tryAcquire()) { long currentTime = System.currentTimeMillis(); // Check how long it has been since we reconnected try { if ((currentTime - connectRequestTime) / 1000 > backoffSeconds) { connectRequestTime = currentTime; timer.newTimeout( new TimerTask() { public void run(Timeout timeout) throws Exception { channelSetter.connect(); } }, backoffSeconds, TimeUnit.SECONDS); } } finally { lock.release(); } } }
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); } }
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(); }
/** Run the bollie thread */ @Override public void run() { golfBall[] ballsCollected; // Array to hold the balls bollie collects while (done.get() != true) { // Check that Range has not closed try { sleep(waitTime.nextInt(5000) + 2000); // Sleep for 2-7 seconds if (done.get() != true) { // Recheck condition for closing, just in case! bollieOnField.set(true); // Set Atomic boolean to true System.out.println("*********** Bollie collecting balls ************"); ballsCollected = sharedField .collectAllBallsFromField(); // Collect balls, no golfers allowed to swing while // this is happening semaphore.drainPermits(); // drain permits so that golfers must wait System.out.println( "*********** Bollie collected " + ballsCollected.length + " balls ************"); sleep(1000); // Simulate collecting and adding sharedStash.addBallsToStash(ballsCollected); // Add collected balls to stash semaphore.release( noGolfers); // Release semaphore and all waiting threads, so that golfers waiting can // continue to their next swing bollieOnField.set(false); // Set Atomic boolean to false, condition no longer blocked } } catch (InterruptedException e) { e.printStackTrace(); } } sharedStash.golfersGo(); }
public RtspClient() { mCSeq = 0; mTmpParameters = new Parameters(); mTmpParameters.port = 1935; mTmpParameters.path = "/"; mTmpParameters.transport = TRANSPORT_UDP; mAuthorization = null; mCallback = null; mMainHandler = new Handler(Looper.getMainLooper()); mState = STATE_STOPPED; final Semaphore signal = new Semaphore(0); new HandlerThread("RtspClient") { @Override protected void onLooperPrepared() { mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == RtpThread.WHAT_THREAD_END_UNEXCEPTION) { if (mCallback != null) { mCallback.onRtspUpdate(RtpThread.WHAT_THREAD_END_UNEXCEPTION, null); } else { stopStream(); } } } }; signal.release(); } }.start(); signal.acquireUninterruptibly(); }
public int getQuotaToUse(int want) { waiterSemaphore.acquireUninterruptibly(); try { // take element from the queue, add the remaining back to the queue Integer q = queue.take(); if (q > want) { queue.put(new Integer(q - want)); // had more than wanted return want; } else if (q <= want) { // had less than wanted return q; } ; // will not happen return 0; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); return 0; } finally { waiterSemaphore.release(); } }
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(); } }
/** Run a job. */ static void runJob(String name, Job job, Machine machine, String startmessage, Util.Timer timer) { JOB_SEMAPHORE.acquireUninterruptibly(); Long starttime = null; try { try { starttime = timer.tick("starting " + name + " ...\n " + startmessage); // initialize and submit a job machine.init(job); job.submit(); // Separate jobs final long sleeptime = 1000L * job.getConfiguration().getInt(JOB_SEPARATION_PROPERTY, 10); if (sleeptime > 0) { Util.out.println(name + "> sleep(" + Util.millis2String(sleeptime) + ")"); Thread.sleep(sleeptime); } } finally { JOB_SEMAPHORE.release(); } if (!job.waitForCompletion(false)) throw new RuntimeException(name + " failed."); } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } finally { if (starttime != null) timer.tick(name + "> timetaken=" + Util.millis2String(timer.tick() - starttime)); } }
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); } }
@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(); }
public void run() { while (running) { try { ignore.acquireUninterruptibly(); if (!running) break; ignore.release(); if (srv == null) srv = new ServerSocket(port); if (connecting == null) { connecting = new ServerConnection(); } if (connecting.connect(srv, password)) { add(connecting); owner.add(connecting, privilege); connecting = null; } } catch (IOException e) { if (running && !isIgnoring()) { owner.println("Port unavailable, please select a different port."); owner.println("Ignoring new connections."); ignore(true); } } } }
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; }
/** * This method checks if the reader thread has finished, and re-throw any exceptions thrown by the * reader thread. * * @throws SqoopException if the consumer thread threw it. * @throws RuntimeException if some other exception was thrown. */ private void waitForConsumer() { try { consumerFuture.get(); } catch (ExecutionException ex) { // In almost all cases, the exception will be SqoopException, // because all exceptions are caught and propagated as // SqoopExceptions // There are race conditions with exceptions where the free sema is // no released. So sense we are in single threaded mode at this point // we can ask if there are availablePermits and release if needed if (free.availablePermits() == 0) { free.release(); } Throwable t = ex.getCause(); if (t instanceof SqoopException) { throw (SqoopException) t; } // In the rare case, it was not a SqoopException Throwables.propagate(t); } catch (Exception ex) { // There are race conditions with exceptions where the free sema is // no released. So sense we are in single threaded mode at this point // we can ask if there are availablePermits and release if needed if (free.availablePermits() == 0) { free.release(); } throw new SqoopException(SparkExecutionError.SPARK_EXEC_0019, ex); } }
private void logState() { logger.debug( "Available permits: {} thread queue: {} state: {} threshold: {}", new Object[] { lock.availablePermits(), lock.getQueueLength(), counter.get(), getThreshold() }); }
public static void unblock(int permits) { Semaphore semaphore = _semaphore; _semaphore = null; semaphore.release(permits); }
@Test public void testEnlargePool() throws Exception { AbstractClientConnectionFactory factory = mock(AbstractClientConnectionFactory.class); when(factory.isRunning()).thenReturn(true); TcpConnectionSupport mockConn1 = makeMockConnection("conn1"); TcpConnectionSupport mockConn2 = makeMockConnection("conn2"); TcpConnectionSupport mockConn3 = makeMockConnection("conn3"); TcpConnectionSupport mockConn4 = makeMockConnection("conn4"); when(factory.getConnection()).thenReturn(mockConn1, mockConn2, mockConn3, mockConn4); CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(factory, 2); cachingFactory.start(); TcpConnection conn1 = cachingFactory.getConnection(); TcpConnection conn2 = cachingFactory.getConnection(); assertNotSame(conn1, conn2); Semaphore semaphore = TestUtils.getPropertyValue( TestUtils.getPropertyValue(cachingFactory, "pool"), "permits", Semaphore.class); assertEquals(0, semaphore.availablePermits()); cachingFactory.setPoolSize(4); TcpConnection conn3 = cachingFactory.getConnection(); TcpConnection conn4 = cachingFactory.getConnection(); assertEquals(0, semaphore.availablePermits()); conn1.close(); conn1.close(); conn2.close(); conn3.close(); conn4.close(); assertEquals(4, semaphore.availablePermits()); }
/** {@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 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(); }
public Map<String, Object> process(Map<String, Object> input) { if (!isValid) { validate(true); } Long currentProcessId = processId.incrementAndGet(); Semaphore resultSemaphoreForProcess = new Semaphore(0); resultSemaphores.put(currentProcessId, resultSemaphoreForProcess); // send input to all input pipeline stages for (PipelineStage inputStage : inputStages.keySet()) { Map<String, String> inputPortMapping = inputStages.get(inputStage); for (String inputPort : inputPortMapping.keySet()) { Object inputParam = input.get(inputPort); inputStage.consume(currentProcessId, inputPortMapping.get(inputPort), inputParam); } } // wait for the output to become ready resultSemaphoreForProcess.acquireUninterruptibly(); if (Boolean.FALSE == processingStatus.remove(currentProcessId)) { Throwable t = processingException.remove(currentProcessId); throw new PipelineProcessingException( "Processing failed for id '" + currentProcessId + "'.", t); } // cleanup and return the result return clear(currentProcessId); }
/** * @return if <0, then this pipe should be stopped. If ==0, it should not wait. If >0, if it * should wait */ int execute() { if (!lock.tryAcquire()) return 1; // currently being accessed Thread myThread = Thread.currentThread(); int threadIndex = -1; for (int i = 0; i < threads.length; i++) { if (threads[i] == null) { threads[i] = myThread; threadIndex = i; break; } if (myThread != threads[i]) continue; threadIndex = i; break; } Signal signal; if (threadIndex < 0) { signal = dummySignal; } else { SignalImpl s = signals[threadIndex]; s.threadIndex = threadIndex; s.signaled = false; signal = s; } boolean hasData; try { hasData = poll(signal, null); } finally { signal.signal(); if (threadIndex < 0) lock.release(); } return 0; }
public void place_order(Company company, int quantity, String buy_sell, byte user_system) { Contract contract = company.create_contract(); Order order = company.create_order(buy_sell, quantity); sem_oid.acquireUninterruptibly(); OpenOrder oo = new OpenOrder(order, company, user_system); open_order_map.put(next_orderId, oo); client.placeOrder(next_orderId, contract, order); String message = df_user.format(Calendar.getInstance().getTime()) + buy_sell + " ORDER placed: " + company.name() + "x" + quantity; message = (user_system == 0) ? message + " BY USER" : message; next_orderId++; sem_oid.release(); q.offer(message); }
public void read( final long position, final long size, final ByteBuffer directByteBuffer, final AIOCallback aioPackage) throws HornetQException { checkOpened(); if (poller == null) { startPoller(); } pendingWrites.countUp(); maxIOSemaphore.acquireUninterruptibly(); try { read(handler, position, size, directByteBuffer, aioPackage); } catch (HornetQException e) { // Release only if an exception happened maxIOSemaphore.release(); pendingWrites.countDown(); throw e; } catch (RuntimeException e) { // Release only if an exception happened maxIOSemaphore.release(); pendingWrites.countDown(); throw e; } }