public void write( final long position, final long size, final ByteBuffer directByteBuffer, final AIOCallback aioCallback) { if (aioCallback == null) { throw new NullPointerException("Null Callback"); } checkOpened(); if (poller == null) { startPoller(); } pendingWrites.countUp(); if (writeExecutor != null) { maxIOSemaphore.acquireUninterruptibly(); writeExecutor.execute( new Runnable() { public void run() { long sequence = nextWritingSequence.getAndIncrement(); try { write(handler, sequence, position, size, directByteBuffer, aioCallback); } catch (HornetQException e) { callbackError( aioCallback, sequence, directByteBuffer, e.getType().getCode(), e.getMessage()); } catch (RuntimeException e) { callbackError( aioCallback, sequence, directByteBuffer, HornetQExceptionType.INTERNAL_ERROR.getCode(), e.getMessage()); } } }); } else { maxIOSemaphore.acquireUninterruptibly(); long sequence = nextWritingSequence.getAndIncrement(); try { write(handler, sequence, position, size, directByteBuffer, aioCallback); } catch (HornetQException e) { callbackError( aioCallback, sequence, directByteBuffer, e.getType().getCode(), e.getMessage()); } catch (RuntimeException e) { callbackError( aioCallback, sequence, directByteBuffer, HornetQExceptionType.INTERNAL_ERROR.getCode(), e.getMessage()); } } }
public void transicion(int tipoHilo, int transicion) { // Entra al monitor ingreso.acquireUninterruptibly(); // El valor de "transicion" representa la transición a disparar // transicion = X significa que quiero disparar TX // HAY QUE TENER ORDENADAS LAS COLUMNAS DE LA MATRIZ DE INCIDENCIA DEL PIPE // Creamos un vector cuyo tamaño sea el número de transiciones, que es el número de columnas // de la matriz de incidencia int[] vectorT = new int[incidencia[0].length]; for (int i = 0; i < incidencia[0].length; i++) { vectorT[i] = 0; } vectorT[transicion] = 1; // Para saber si la transición está habilitada, el monitor multiplica la matriz de incidencia // por el vector de disparo, y lo suma al vector de marcado actual. Si algún elemento del vector // resultante es menor a cero, no está habilitada esa transición. De lo contrario, el marcado // actual es reemplazado por el vector resultante. marcado = sensibilidad(incidencia, vectorT, tipoHilo); // Liberar Cola liberarCola(); // Libero el monitor ingreso.release(); return; }
/** 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)); } }
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 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; } }
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 void start() { gatewayThread = new Thread(new GatewayRunner()); feedbackThread = new Thread(new FeedbackRunner()); gatewayThread.start(); feedbackThread.start(); startUp.acquireUninterruptibly(2); }
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); }
@Test public void noExecutableFound() { System.err.println("Starting test noExecutableFound()"); final Semaphore semaphore = new Semaphore(0); final AtomicInteger exitCode = new AtomicInteger(); NuProcessHandler processListener = new NuAbstractProcessHandler() { @Override public void onExit(int statusCode) { exitCode.set(statusCode); semaphore.release(); } }; NuProcessBuilder pb = new NuProcessBuilder(processListener, "/bin/zxczxc"); NuProcess process = pb.start(); semaphore.acquireUninterruptibly(); Assert.assertFalse("Process incorrectly reported running", process.isRunning()); Assert.assertEquals( "Output did not matched expected result", Integer.MIN_VALUE, exitCode.get()); System.err.println("Completed test noExecutableFound()"); }
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); }
private void schedule() { queueSize.acquireUninterruptibly(); for (Map.Entry<String, WeightedQueue> request : queues.entrySet()) { WeightedQueue queue = request.getValue(); // Using the weight, process that many requests at a time (for that scheduler id) for (int i = 0; i < queue.weight; i++) { Thread t = queue.poll(); if (t == null) break; else { taskCount.acquireUninterruptibly(); queueSize.acquireUninterruptibly(); } } } queueSize.release(); }
/** * Return stream state * * @return StreamState */ public StreamState getState() { try { lock.acquireUninterruptibly(); return state; } finally { lock.release(); } }
public static Handler getHandler() { if (_handler == null) { _ready.acquireUninterruptibly(); _ready.release(); } return _handler; }
public void acquireRead() { assert (!readLocks.contains(Thread.currentThread())); if (!lock.tryAcquire()) { WorkerThread.beginIO(); lock.acquireUninterruptibly(); WorkerThread.endIO(); } readLocks.add(Thread.currentThread()); }
void offer(Action action) { if (DEBUG) { assertOnIcThread(); Log.d( LOGTAG, "offer: Action(" + getConstantName(Action.class, "TYPE_", action.mType) + ")"); } /* Events don't need update because they generate text/selection notifications which will do the updating for us */ if (action.mType != Action.TYPE_EVENT && action.mType != Action.TYPE_ACKNOWLEDGE_FOCUS && action.mType != Action.TYPE_SET_HANDLER) { action.mShouldUpdate = mUpdateGecko; } if (mActions.isEmpty()) { mActionsActive.acquireUninterruptibly(); mActions.offer(action); } else synchronized (this) { // tryAcquire here in case Gecko thread has just released it mActionsActive.tryAcquire(); mActions.offer(action); } switch (action.mType) { case Action.TYPE_EVENT: case Action.TYPE_SET_SELECTION: case Action.TYPE_SET_SPAN: case Action.TYPE_REMOVE_SPAN: case Action.TYPE_SET_HANDLER: onImeSynchronize(); break; case Action.TYPE_REPLACE_TEXT: // try key events first sendCharKeyEvents(action); // fall-through case Action.TYPE_COMPOSE_TEXT: onImeReplaceText( action.mStart, action.mEnd, action.mSequence.toString(), action.mType == Action.TYPE_COMPOSE_TEXT); break; case Action.TYPE_ACKNOWLEDGE_FOCUS: onImeAcknowledgeFocus(); break; default: throw new IllegalStateException("Action not processed"); } ++mIcUpdateSeqno; }
@Override public void run() { logger.info("begin to consume tweets"); controller.running(); while (true) { susSem.acquireUninterruptibly(); try { for (Entry<String, List<Status>> topicData : consumer.nextStatus().entrySet()) { try { // 在高速转发的情况下,这样可以减轻写入到kafka中的状态数据 Map<String, TimeSeriesUpdateState> states = new HashMap<String, TimeSeriesUpdateState>(); List<TimeSeriesUpdateState> segSignal = new ArrayList<TimeSeriesUpdateState>(); for (Status cur : topicData.getValue()) { tweetDao.putTweet(cur); if (cur.getRetweetedStatus() != null) { // rand.nextFloat() < 0.01 && if (tweetDao.getStatusByMid(cur.getRetweetedStatus().getMid()) == null) { tweetDao.putTweet(cur.getRetweetedStatus()); } tweetDao.putRtweet(cur); for (TimeSeriesUpdateState state : tweetDao.updateRtTimeSeries(cur)) { states.put(state.getMid(), state); } } else { // maybe it is the first tweet or an indication // for end of monitoring if (cur.getMid() != null) { SegState state = segDao.getSegState(cur.getMid()); if (state != null) { long updateDate = DateUtil.roundByHour(System.currentTimeMillis()); segSignal.add(new TimeSeriesUpdateState(state.mid, updateDate, true)); List<String> mids = tweetDao.getRtMids(state.mid); for (String rtMid : mids) { segSignal.add(new TimeSeriesUpdateState(rtMid, updateDate, true)); } } } } } for (TimeSeriesUpdateState state : segSignal) { states.put(state.mid, state); } for (TimeSeriesUpdateState state : states.values()) { logger.info("update time series " + state); producer.storeTsUpdateState(state); } } catch (Exception ex) { ex.printStackTrace(); } } } finally { susSem.release(); } } }
public void queue(Thread t, String id, long timeoutMS) throws TimeoutException { WeightedQueue weightedQueue = getWeightedQueue(id); try { queueSize.release(); try { weightedQueue.put(t, timeoutMS); // the scheduler will release us when a slot is available } catch (TimeoutException e) { queueSize.acquireUninterruptibly(); throw e; } catch (InterruptedException e) { queueSize.acquireUninterruptibly(); throw e; } } catch (InterruptedException e) { throw new RuntimeException("Interrupted while queueing requests", e); } }
/** * Sets the stream state * * @param state */ public void setState(StreamState state) { if (!this.state.equals(state)) { try { lock.acquireUninterruptibly(); this.state = state; } finally { lock.release(); } } }
public void run() { int number = start; while (number <= limit) { from.acquireUninterruptibly(); System.out.println(getName() + ": " + number); number += step; to.release(); } }
public void startGLThread() { Log.d(TAG, "Thread started."); if (mTextureManager == null) { mTextureManager = new TextureManager(); } if (mTextureManager.getSurfaceTexture() == null) { mThread = new Thread(SurfaceView.this); mRunning = true; mThread.start(); mLock.acquireUninterruptibly(); } }
public void acquireWrite() { assert (!readLocks.contains(Thread.currentThread())); if (!lock.tryAcquire(MAX_PERMITS)) { WorkerThread.beginIO(); lock.acquireUninterruptibly(MAX_PERMITS); WorkerThread.endIO(); } synchronized (this) { assert (writeLock == null); writeLock = Thread.currentThread(); } }
private int[] sensibilidad(int[][] incidencia, int[] vectorT, int tipoHilo) { boolean habilitado = false; int[] producto; int[] resultado = null; while (!habilitado) { boolean negativo = false; // Bandera que detecta valores negativos en el vector producto = matriz_por_vector(incidencia, vectorT); resultado = suma_vectorial(producto, marcado); for (int j = 0; j < resultado.length; j++) { if (resultado[j] < 0) { negativo = true; } } // Finalizado el cálculo, si la transición está habilitada modifico el marcado, y despierto // al hilo asociado. Caso contrario, el hilo actual va a ir a su respectiva cola a esperar. if (!negativo) { habilitado = true; } else { // Aquí mando el hilo a la cola que corresponda, dependiendo si es un hilo de incio de línea // o un hilo común. También libero el semáforo de ingreso a monitor. if (tipoHilo == 1) { ingreso.release(); colaInicial.acquireUninterruptibly(); ingreso.acquireUninterruptibly(); // Me voy al final de la cola de ingreso al monitor } else if (tipoHilo == 0) { ingreso.release(); colaComun.acquireUninterruptibly(); ingreso.acquireUninterruptibly(); // Me voy al final de la cola de ingreso al monitor } } } return resultado; }
@Test public void testQueuedJobRunsAfterShutdown() throws InterruptedException { OutOfBandScheduledExecutor scheduler = new OutOfBandScheduledExecutor(); ExecutorService worker = Executors.newSingleThreadExecutor(); try { PartitionedScheduledExecutor executor = new PartitionedScheduledExecutor(scheduler, worker); final Semaphore jobSemaphore = new Semaphore(0); final Semaphore testSemaphore = new Semaphore(0); executor.submit( new Callable<Void>() { @Override public Void call() throws Exception { testSemaphore.release(); jobSemaphore.acquireUninterruptibly(); return null; } }); executor.submit( new Callable<Void>() { @Override public Void call() throws Exception { jobSemaphore.acquireUninterruptibly(); return null; } }); testSemaphore.acquireUninterruptibly(); executor.shutdown(); assertThat(executor.awaitTermination(100, MILLISECONDS), is(false)); assertThat(executor.isShutdown(), is(true)); assertThat(executor.isTerminated(), is(false)); jobSemaphore.release(); assertThat(executor.awaitTermination(100, MILLISECONDS), is(false)); assertThat(executor.isShutdown(), is(true)); assertThat(executor.isTerminated(), is(false)); jobSemaphore.release(); assertThat(executor.awaitTermination(2, MINUTES), is(true)); assertThat(executor.isShutdown(), is(true)); assertThat(executor.isTerminated(), is(true)); assertThat(jobSemaphore.availablePermits(), is(0)); } finally { worker.shutdown(); } }
protected void request_mktData(Company company) { Contract contract = company.create_contract(); Vector<TagValue> mkt_data_options = new Vector<TagValue>(); sem_oid.acquireUninterruptibly(); OpenRequest or = new OpenRequest(company, -1); open_request_map.put(next_orderId, or); client.reqMktData(next_orderId, contract, null, true, mkt_data_options); next_orderId++; sem_oid.release(); }
public int remaining() { waiterSemaphore.acquireUninterruptibly(); try { int ret = 0; for (Integer i : queue) { ret += i; } return ret; } finally { waiterSemaphore.release(); } }
void syncWithGecko() { if (DEBUG) { assertOnIcThread(); } if (mFocused && !mActions.isEmpty()) { if (DEBUG) { Log.d(LOGTAG, "syncWithGecko blocking on thread " + Thread.currentThread().getName()); } mActionsActive.acquireUninterruptibly(); mActionsActive.release(); } else if (DEBUG && !mFocused) { Log.d(LOGTAG, "skipped syncWithGecko (no focus)"); } }
public DataSet request_histData(Company company, int long_short_volatility) { Contract contract = company.create_contract(); Vector<TagValue> mkt_data_options = new Vector<TagValue>(); sem_oid.acquireUninterruptibly(); OpenRequest or = new OpenRequest(company, long_short_volatility); open_request_map.put(next_orderId, or); this.date = Calendar.getInstance().getTime(); if (long_short_volatility == 0) client.reqHistoricalData( next_orderId, contract, df_ib.format(this.date), "1800 S", "30 mins", "TRADES", 1, 1, mkt_data_options); else if (long_short_volatility == 1) client.reqHistoricalData( next_orderId, contract, df_ib.format(this.date), parent.data_period, parent.data_granularity, "TRADES", 1, 1, mkt_data_options); else client.reqHistoricalData( next_orderId, contract, df_ib.format(calendar.getTime()), "1 D", "1 hour", "TRADES", 1, 1, mkt_data_options); next_orderId++; sem_oid.release(); return null; }
@Test public void decodingShortUtf8Data() throws Exception { Semaphore semaphore = new Semaphore(0); String SHORT_UNICODE_TEXT = "Hello \uD83D\uDCA9 world"; System.err.println("Starting test decodingShortUtf8Data()"); Utf8DecodingListener processListener = new Utf8DecodingListener(semaphore, SHORT_UNICODE_TEXT); NuProcessBuilder pb = new NuProcessBuilder(processListener, command); pb.start(); semaphore.acquireUninterruptibly(); Assert.assertEquals( "Decoding mismatch", SHORT_UNICODE_TEXT, processListener.decodedStdout.toString()); Assert.assertEquals("Exit code mismatch", 0, processListener.exitCode); Assert.assertFalse("Decoder stdin should not overflow", processListener.stdinOverflow); System.err.println("Completed test decodingShortUtf8Data()"); }
/** Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer data) throws IOException { if (this.field_149281_e == null) { deflateGate.acquireUninterruptibly(); if (this.field_149281_e == null) { deflate(); } deflateGate.release(); } data.writeInt(this.field_149284_a); data.writeInt(this.field_149282_b); data.writeBoolean(this.field_149279_g); data.writeShort((short) (this.field_149283_c & 65535)); data.writeShort((short) (this.field_149280_d & 65535)); data.writeInt(this.field_149285_h); data.writeBytes(this.field_149281_e, 0, this.field_149285_h); }