Example usage for java.util.concurrent Semaphore Semaphore

List of usage examples for java.util.concurrent Semaphore Semaphore

Introduction

In this page you can find the example usage for java.util.concurrent Semaphore Semaphore.

Prototype

public Semaphore(int permits) 

Source Link

Document

Creates a Semaphore with the given number of permits and nonfair fairness setting.

Usage

From source file:org.apache.flume.client.avro.TestReliableSpoolingFileEventReader.java

@Test
public void testConsumeFileRandomlyNewFile() throws Exception {
    // Atomic moves are not supported in Windows.
    if (SystemUtils.IS_OS_WINDOWS) {
        return;/*ww w.j a  va2 s.  co m*/
    }
    final ReliableEventReader reader = new ReliableSpoolingFileEventReader.Builder().spoolDirectory(WORK_DIR)
            .consumeOrder(ConsumeOrder.RANDOM).build();
    File fileName = new File(WORK_DIR, "new-file");
    FileUtils.write(fileName, "New file created in the end. Shoud be read randomly.\n");
    Set<String> expected = Sets.newHashSet();
    int totalFiles = WORK_DIR.listFiles().length;
    final Set<String> actual = Sets.newHashSet();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    final Semaphore semaphore1 = new Semaphore(0);
    final Semaphore semaphore2 = new Semaphore(0);
    Future<Void> wait = executor.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            readEventsForFilesInDir(WORK_DIR, reader, actual, semaphore1, semaphore2);
            return null;
        }
    });
    semaphore1.acquire();
    File finalFile = new File(WORK_DIR, "t-file");
    FileUtils.write(finalFile, "Last file");
    semaphore2.release();
    wait.get();
    int listFilesCount = ((ReliableSpoolingFileEventReader) reader).getListFilesCount();
    finalFile.delete();
    createExpectedFromFilesInSetup(expected);
    expected.add("");
    expected.add("New file created in the end. Shoud be read randomly.");
    expected.add("Last file");
    Assert.assertTrue(listFilesCount < (totalFiles + 2));
    Assert.assertEquals(expected, actual);
}

From source file:com.pinterest.pinlater.client.PinLaterQueryIssuer.java

private void issueDequeueAckRequests(final PinLater.ServiceIface iface) throws InterruptedException {
    Preconditions.checkNotNull(queueName, "Queue was not specified.");
    final AtomicLong queriesIssued = new AtomicLong(0);
    final Semaphore permits = new Semaphore(concurrency);
    while (numQueries == -1 || queriesIssued.get() < numQueries) {
        final PinLaterDequeueRequest request = new PinLaterDequeueRequest();
        request.setQueueName(queueName);
        request.setLimit(batchSize);//from   w w  w  .j  a va2s .c  o  m
        final long startTimeNanos = System.nanoTime();
        queriesIssued.incrementAndGet();
        permits.acquire();
        iface.dequeueJobs(REQUEST_CONTEXT, request)
                .flatMap(new Function<PinLaterDequeueResponse, Future<Void>>() {
                    @Override
                    public Future<Void> apply(PinLaterDequeueResponse response) {
                        if (response.getJobsSize() == 0) {
                            return Future.Void();
                        }

                        PinLaterJobAckRequest jobAckRequest = new PinLaterJobAckRequest(queueName);
                        for (String job : response.getJobs().keySet()) {
                            if (random.nextInt(100) < dequeueSuccessPercent) {
                                jobAckRequest.addToJobsSucceeded(new PinLaterJobAckInfo(job));
                            } else {
                                jobAckRequest.addToJobsFailed(new PinLaterJobAckInfo(job));
                            }
                        }
                        return iface.ackDequeuedJobs(REQUEST_CONTEXT, jobAckRequest);
                    }
                }).respond(new Function<Try<Void>, BoxedUnit>() {
                    @Override
                    public BoxedUnit apply(Try<Void> voidTry) {
                        permits.release();
                        statsLogger
                                .requestComplete(Duration.fromNanoseconds(System.nanoTime() - startTimeNanos));
                        if (voidTry.isThrow()) {
                            LOG.info("Exception for request: " + request + " : " + ((Throw) voidTry).e());
                        }
                        return BoxedUnit.UNIT;
                    }
                });
    }
    permits.acquire(concurrency);
    LOG.info("Dequeue/ack queries issued: " + queriesIssued);
}

From source file:com.digium.respokesdk.RespokeCall.java

/**
 *  Common constructor logic//ww  w .  j  a  v  a  2s.  com
 *
 *  @param channel  The signaling channel to use for the call
 */
private void commonConstructor(RespokeSignalingChannel channel) {
    signalingChannel = channel;
    iceServers = new ArrayList<PeerConnection.IceServer>();
    queuedLocalCandidates = new ArrayList<IceCandidate>();
    queuedRemoteCandidates = new ArrayList<IceCandidate>();
    collectedLocalCandidates = new ArrayList<IceCandidate>();
    sessionID = Respoke.makeGUID();
    timestamp = new Date();
    queuedRemoteCandidatesSemaphore = new Semaphore(1); // remote candidates queue mutex
    localCandidatesSemaphore = new Semaphore(1); // local candidates queue mutex

    if (null != signalingChannel) {
        RespokeSignalingChannel.Listener signalingChannelListener = signalingChannel.GetListener();
        if (null != signalingChannelListener) {
            signalingChannelListener.callCreated(this);
        }
    }

    //TODO resign active handler?
}

From source file:com.cwp.android.baidutest.MyApplication.java

public static void startMaInfoMonitoring() {

    //?MaInfo?//w ww.j a va  2  s .  c  o  m
    BmobRealTimeData rtd = new BmobRealTimeData();

    //start?
    //??
    rtd.start(mContext, new ValueEventListener() {
        @Override
        public void onConnectCompleted() {
            //?
            Log.d("->MyApplication", "BmobRealTimeData->currentThread=" + Thread.currentThread());
            Log.d("->MyApplication", "BmobRealTimeData->?:" + rtd.isConnected());

            //?
            if (rtd.isConnected()) {
                rtd.subTableUpdate("MaInfo");
            }
        }

        @Override
        public void onDataChange(JSONObject jsonObject) {
            //

            new Thread(() -> {
                Log.d("->MyApplication", "onDataChange->currentThread=" + Thread.currentThread());
                Log.d("->MyApplication",
                        "onDataChange->(" + jsonObject.optString("action") + ")\n?" + jsonObject);

                if (BmobRealTimeData.ACTION_UPDATETABLE.equals(jsonObject.optString("action"))) {
                    JSONObject data = jsonObject.optJSONObject("data");

                    Log.d("->MyApplication", "onDataChange->?");
                    String username = data.optString("username");
                    String vin = data.optString("vin");

                    try {
                        mSyncSemaphore.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    //?????????????
                    List<AutoInfo> list = AutoInfoLocalDBOperation
                            .queryBy(mContext,
                                    AutoInfoConstants.COLUMN_USERNAME + " = ? and "
                                            + AutoInfoConstants.COLUMN_VIN + " = ?",
                                    new String[] { username, vin });
                    if (list.size() != 0) {
                        Log.d("->MyApplication", "onDataChange->?");
                        //?
                        AutoInfo autoInfo = list.get(0);
                        String brand = autoInfo.getBrand();
                        String model = autoInfo.getModel();
                        String plateNum = autoInfo.getLicensePlateNum();
                        Message message = Message.obtain();
                        message.what = -1;
                        message.obj = brand + " " + model + " " + plateNum;
                        //???????
                        if (data.optInt("gasolineVolume") < 20) {//?<20%
                            //
                            mHandler.sendEmptyMessage(1);
                        }

                        //?15000?
                        //?1500?(??)?????

                        //???

                        //??5.E.a-c,????
                        //????
                        Semaphore semaphore = new Semaphore(1);
                        double mileage = data.optDouble("mileage");
                        //mileage?15000??
                        if (mileage >= 15000) {
                            try {
                                semaphore.acquire();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            String scanTime = data.optString("scanTime");
                            BmobQuery<MaInfo> query = new BmobQuery<MaInfo>();
                            query.addWhereEqualTo("username", username);
                            query.addWhereEqualTo("vin", vin);
                            query.addWhereLessThan("scanTime", scanTime);
                            query.addQueryKeys("scanTime");
                            query.order("-scanTime");
                            final Semaphore finalSemaphore = semaphore;
                            query.findObjects(mContext, new FindListener<MaInfo>() {
                                @Override
                                public void onSuccess(List<MaInfo> list) {
                                    int current = (int) mileage / 15000;
                                    Log.d("", "current=" + current + ",mileage=" + mileage);
                                    if (list.size() == 0) {
                                        message.obj = current;
                                        message.what = 2;
                                        mHandler.sendMessage(message);
                                    } else {
                                        double lastMileage = list.get(0).getMileage();
                                        int last = (int) lastMileage / 15000;
                                        if (current > last) {
                                            Message message = Message.obtain();
                                            message.obj = current;
                                            message.what = 2;
                                            mHandler.sendMessage(message);
                                        }
                                    }
                                    finalSemaphore.release();
                                }

                                @Override
                                public void onError(int i, String s) {
                                    finalSemaphore.release();
                                }
                            });
                        }

                        try {
                            semaphore.acquire();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //???????????
                        if (data.optString("enginePerfor").equals("")) {//?
                            mHandler.sendEmptyMessage(3);
                        }
                        if (data.optString("lamp").equals("")) {//?
                            mHandler.sendEmptyMessage(4);
                        }
                        if (data.optString("transmissionPerfor").equals("")) {//?
                            mHandler.sendEmptyMessage(5);
                        }
                        semaphore.release();

                        //????
                        mHandler.sendEmptyMessage(0);
                        mSyncSemaphore.release();
                        Log.d("++++++++++++++++++++", "++++++++++++++++");
                    } else {
                        mSyncSemaphore.release();
                    }
                }
            }).start();
        }
    });
}

From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java

/**
 * Perform asynchronous operations nodes.
 * /*from w  w  w  .j  a v a 2  s . c om*/
 * @param nodeList
 *            {@link Collection}
 * @return <code>true</code>, if successful
 */
private boolean validate(Collection<String> nodeList) throws AnkushException {
    try {
        // Create semaphore to join threads
        final Semaphore semaphore = new Semaphore(nodeList.size());
        for (final String host : nodeList) {
            final NodeConfig nodeConfig = clusterConfig.getNodes().get(host);
            semaphore.acquire();
            AppStoreWrapper.getExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    nodeConfig.setStatus(new CassandraValidator(clusterConfig, nodeConfig).validate());

                    if (semaphore != null) {
                        semaphore.release();
                    }
                }

            });
        }
        semaphore.acquire(nodeList.size());
    } catch (Exception e) {
        throw new AnkushException(getComponentName() + " validation failed.");
    }
    return AnkushUtils.getStatus(clusterConfig, nodeList);
}

From source file:com.pinterest.rocksplicator.controller.DispatcherTest.java

@Test
public void testRetryTask() throws Exception {
    final String errorMsg = "Boom!!!";
    TaskBase task = new ThrowingTask(errorMsg).retry(3).getEntity();
    final CountDownLatch latch = new CountDownLatch(3);
    FIFOTaskQueue tq = new FIFOTaskQueue(10) {
        @Override//  w  w w . j av  a  2s.  com
        public boolean finishTask(final long id, final String output) {
            latch.countDown();
            return super.finishTask(id, output);
        }

        @Override
        public long finishTaskAndEnqueueRunningTask(final long id, final String output, final TaskBase newTask,
                final String worker) {
            latch.countDown();
            return super.finishTaskAndEnqueueRunningTask(id, output, newTask, worker);
        }
    };
    tq.enqueueTask(task, Integer.toString(++nameCounter), 0);

    Semaphore idleWorkersSemaphore = new Semaphore(2);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(2));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, tq);
    TaskDispatcher dispatcher = new TaskDispatcher(2, idleWorkersSemaphore, workerPool, tq);
    dispatcher.start();

    Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
    Assert.assertEquals(tq.getResult(0), errorMsg);
    Assert.assertEquals(tq.getResult(1), errorMsg);
    Assert.assertEquals(tq.getResult(2), errorMsg);
    dispatcher.stop();
}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testCompoundUnits() throws InterruptedException {
    _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> {
        // Annotations
        Assert.assertEquals(0, r.getAnnotationsCount());

        // Dimensions
        Assert.assertEquals(0, r.getDimensionsCount());

        // Samples
        Assert.assertEquals(0, r.getTimersCount());
        Assert.assertEquals(0, r.getTimersCount());
        assertSample(r.getGaugesList(), "gauge", 10d, ClientV2.Unit.Type.Value.BIT,
                ClientV2.Unit.Scale.Value.UNIT, ClientV2.Unit.Type.Value.SECOND,
                ClientV2.Unit.Scale.Value.UNIT);
    })).willReturn(WireMock.aResponse().withStatus(200)));

    final Semaphore semaphore = new Semaphore(0);
    final Sink sink = new ApacheHttpSink.Builder()
            .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH))
            .setEventHandler(new CompletionHandler(semaphore)).build();

    final TsdEvent event = new TsdEvent(Collections.emptyMap(), createQuantityMap(), createQuantityMap(),
            createQuantityMap("gauge", TsdQuantity.newInstance(10d, Units.BITS_PER_SECOND)));

    sink.record(event);//from  w w w  .  ja va  2 s  .c  om
    semaphore.acquire();

    // Request matcher
    final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH))
            .withHeader("Content-Type", WireMock.equalTo("application/octet-stream"));

    // Assert that data was sent
    _wireMockRule.verify(1, requestPattern);
    Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty());
}

From source file:org.bart452.runningshoesensor.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestPermission();//from  w  w  w  .j  a v  a  2s .  co m
    context = getApplicationContext();

    mHeaderImageView = (ImageView) findViewById(R.id.appBarIv);
    Picasso.with(context).load(R.drawable.sunset_road_landscape).into(mHeaderImageView);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.toolBar);
    setSupportActionBar(mToolbar);
    mCollapsingTb = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);
    mCollapsingTb.setTitle("Shoe sensor");
    mCollapsingTb.setExpandedTitleGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);

    // Bluetooth
    final BluetoothManager mBleMan = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBleAdapter = mBleMan.getAdapter();
    mBleScanner = mBleAdapter.getBluetoothLeScanner();
    mCharList = new ArrayList<>();
    mBleSem = new Semaphore(1);
    mBleThread = new BleThread(mBleSem);
    mBleThread.start();

    mBleReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
                if (mBleAdapter.getState() == BluetoothAdapter.STATE_ON) {
                    Log.d(LOG_TAG, "BT ON");
                    mScanFab.setEnabled(true);
                    if (mSnackBar != null) {
                        if (mSnackBar.isShown())
                            mSnackBar.dismiss();
                    }
                } else {
                    mScanFab.setEnabled(false);
                    bleEnable();
                }
            }
        }
    };

    // Text
    mDevNameTv = (TextView) findViewById(R.id.devNameTv);
    mDevNameTv.setText(getString(R.string.device_name) + " No device found");
    mRssiTv = (TextView) findViewById(R.id.rssiTv);
    mAddrTv = (TextView) findViewById(R.id.devAddrTv);

    // Buttons and switches
    mScanFab = (FloatingActionButton) findViewById(R.id.scanFab);
    mScanFab.setOnClickListener(this);
    mConnSwitch = (Switch) findViewById(R.id.connSwitch);
    mConnSwitch.setOnClickListener(this);

    //Graph
    mDataGraph = (GraphView) findViewById(R.id.dataGraph);
    mDataXSeries = new LineGraphSeries<>();
    mDataYSeries = new LineGraphSeries<>();
    mDataYSeries.setBackgroundColor(Color.RED);
    mDataGraph.addSeries(mDataXSeries);
    mDataGraph.addSeries(mDataYSeries);
    mDataGraph.getViewport().setXAxisBoundsManual(true);
    mDataGraph.getViewport().setMinX(0);
    mDataGraph.getViewport().setMaxX(20);

    // Animation
    mRotateAnim = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);
    mRotateAnim.setDuration(SCAN_PERIOD);
    mRotateAnim.setInterpolator(new LinearInterpolator());
    bleEnable();
}

From source file:com.all.app.ApplicationUtils.java

public static void showFrameAndWaitForClose(Window window) {
    try {/*from w ww  .  j a  v  a 2 s. c  o  m*/
        final Semaphore lock = new Semaphore(0);
        window.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                lock.release();
            }
        });
        window.setVisible(true);
        lock.acquire();
    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:com.netflix.curator.framework.imps.TestFrameworkEdges.java

@Test
public void testRetry() throws Exception {
    final int MAX_RETRIES = 3;
    final int serverPort = server.getPort();

    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 1000, 1000,
            new RetryOneTime(10));
    client.start();//w  ww  .  jav  a  2  s  .c  om
    try {
        final AtomicInteger retries = new AtomicInteger(0);
        final Semaphore semaphore = new Semaphore(0);
        client.getZookeeperClient().setRetryPolicy(new RetryPolicy() {
            @Override
            public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) {
                semaphore.release();
                if (retries.incrementAndGet() == MAX_RETRIES) {
                    try {
                        server = new TestingServer(serverPort);
                    } catch (Exception e) {
                        throw new Error(e);
                    }
                }
                return true;
            }
        });

        server.stop();

        // test foreground retry
        client.checkExists().forPath("/hey");
        Assert.assertTrue(semaphore.tryAcquire(MAX_RETRIES, 10, TimeUnit.SECONDS));

        semaphore.drainPermits();
        retries.set(0);

        server.stop();

        // test background retry
        client.checkExists().inBackground().forPath("/hey");
        Assert.assertTrue(semaphore.tryAcquire(MAX_RETRIES, 10, TimeUnit.SECONDS));
    } catch (Throwable e) {
        Assert.fail("Error", e);
    } finally {
        IOUtils.closeQuietly(client);
    }
}