Example usage for java.util.concurrent Semaphore acquire

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

Introduction

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

Prototype

public void acquire() throws InterruptedException 

Source Link

Document

Acquires a permit from this semaphore, blocking until one is available, or the thread is Thread#interrupt interrupted .

Usage

From source file:org.apache.kylin.storage.hbase.util.HbaseStreamingInput.java

public static void randomScan(String tableName) throws IOException {

    final Semaphore semaphore = new Semaphore(0);
    new Thread(new Runnable() {
        @Override//  ww  w  . ja  v a  2 s .co  m
        public void run() {
            scheduleJob(semaphore, 60000);//1 minutes a batch
        }
    }).start();

    while (true) {
        try {
            semaphore.acquire();
            int waiting = semaphore.drainPermits();
            if (waiting > 0) {
                logger.warn("Too many queries to handle! Blocking " + waiting + " sets of scan requests");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }

        Random r = new Random();
        Connection conn = getConnection();
        Table table = conn.getTable(TableName.valueOf(tableName));

        long leftBound = getFirstKeyTime(table);
        long rightBound = System.currentTimeMillis();

        for (int t = 0; t < 5; ++t) {
            long start = (long) (leftBound + r.nextDouble() * (rightBound - leftBound));
            long end = start + 600000;//a period of 10 minutes
            logger.info("A scan from " + formatTime(start) + " to " + formatTime(end));

            Scan scan = new Scan();
            scan.setStartRow(Bytes.toBytes(start));
            scan.setStopRow(Bytes.toBytes(end));
            scan.addFamily(CF);
            ResultScanner scanner = table.getScanner(scan);
            long hash = 0;
            int rowCount = 0;
            for (Result result : scanner) {
                Cell cell = result.getColumnLatestCell(CF, QN);
                byte[] value = cell.getValueArray();
                if (cell.getValueLength() != CELL_SIZE) {
                    logger.error("value size invalid!!!!!");
                }

                hash += Arrays.hashCode(Arrays.copyOfRange(value, cell.getValueOffset(),
                        cell.getValueLength() + cell.getValueOffset()));
                rowCount++;
            }
            scanner.close();
            logger.info("Scanned " + rowCount + " rows, the (meaningless) hash for the scan is " + hash);
        }
        table.close();
        conn.close();
    }
}

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

public static void startMaInfoMonitoring() {

    //?MaInfo?//from   w ww.  j a v a2 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:hudson.plugins.android_emulator.SdkInstaller.java

/**
 * Acquires an exclusive lock for the machine we're executing on.
 * <p>//  w  ww . j a  v a2  s  . c o  m
 * The lock only has one permit, meaning that other executors on the same node which want to
 * install SDK components will block here until the lock is released by another executor.
 *
 * @return The semaphore for the current machine, which must be released once finished with.
 */
private static Semaphore acquireLock() throws InterruptedException {
    // Retrieve the lock for this node
    Semaphore semaphore;
    final Node node = Computer.currentComputer().getNode();
    synchronized (node) {
        semaphore = mutexByNode.get(node);
        if (semaphore == null) {
            semaphore = new Semaphore(1);
            mutexByNode.put(node, semaphore);
        }
    }

    // Block until the lock is available
    semaphore.acquire();
    return semaphore;
}

From source file:org.minig.imap.command.Command.java

private void lock(Semaphore lock) {
    try {/*from  www  .ja va  2 s. c om*/
        lock.acquire();
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:ch.admin.suis.msghandler.sender.SenderJob.java

@SuppressWarnings("unchecked")
@Override//from  ww w . ja v a  2 s  .  c  o  m
public void execute(JobExecutionContext context) throws JobExecutionException {
    LOG.debug("sender job started");

    // get the objects that are necessary for the sender
    JobDataMap dataMap = context.getJobDetail().getJobDataMap();

    final MessageHandlerContext handlerContext = (MessageHandlerContext) dataMap
            .get(MessageHandlerContext.MESSAGE_HANDLER_CONTEXT_PARAM);
    final List<Outbox> outbox = (List<Outbox>) dataMap.get(MessageHandlerContext.OUTBOX_PARAM);

    // pre-conditions check
    Validate.notNull(handlerContext);
    Validate.notNull(outbox);

    Semaphore sequenceLock = handlerContext.getSequenceLock();

    try {
        sequenceLock.acquire();

        try {
            if (this instanceof TransparentSenderJob) {
                new Sender().execute(new TransparentSenderSessionImpl(handlerContext, outbox));
            } else {
                new Sender().execute(new SenderSessionImpl(handlerContext, outbox));
            }
        } finally {
            sequenceLock.release();
        }
    } catch (InterruptedException e) {
        LOG.info("sender terminated while waiting for other jobs to complete");
        Thread.currentThread().interrupt();
    }
}

From source file:org.marketcetera.saclient.SAClientWSTest.java

private static <R> void verifyInvocationCannotBeInterrupted(final WSTester<R> inTester) throws Exception {
    resetServiceParameters();//from  w  ww  .  j a va  2s.  c om
    getMockSAService().setSleep(true);
    inTester.setReturnValue(false);
    final Semaphore sema = new Semaphore(0);
    final AtomicReference<Exception> interruptFailure = new AtomicReference<Exception>();
    Thread t = new Thread() {
        @Override
        public void run() {
            sema.release();
            try {
                inTester.invokeApi(false);
            } catch (Exception ex) {
                interruptFailure.set(ex);
            }
        }
    };
    t.start();
    //Wait for the thread to be started
    sema.acquire();
    //Interrupt it as soon as it is found started
    t.interrupt();
    //wait for it to end
    t.join();
    //verify that we are not able to interrupt it
    assertNull("API invocation got interrupted!", interruptFailure.get());
}

From source file:org.apache.asterix.experiment.client.StatisticsQueryGenerator.java

public void start() throws Exception {
    final Semaphore sem = new Semaphore(0);
    threadPool.submit(new QueryGenerator(sem, config));
    sem.acquire();
}

From source file:com.bt.aloha.collections.memory.InMemoryHousekeepingCollectionImpl.java

public void housekeep() {
    try {//from   ww w . j  a  v a 2s  . c om
        log.info(String.format("Housekeeping: info table size is %d", size()));

        List<String> expiredNotDead = new ArrayList<String>();
        for (String id : getAll().keySet()) {
            Semaphore s = getSemaphores().get(id);
            s.acquire();
            try {
                T info = getAll().get(id);
                log.info(String.format(
                        "Housekeeping: trying to housekeep info %s (forced=%s, expired=%s, dead=%s, TTL=%d)",
                        id, info.isHousekeepForced(), isExpired(info), info.isDead(), maxTimeToLive));
                if (isExpired(info) || info.isHousekeepForced())
                    if (info.isDead() || info.isHousekeepForced()) {
                        log.info(String.format("Housekeeping: found an 'old' info, removing: %s", id));
                        getAll().remove(id);
                        getSemaphores().remove(id);
                    } else
                        expiredNotDead.add(id);
                else
                    log.debug(String
                            .format("Housekeeping: info %s has not expired yet and will not be housekept", id));
            } catch (Throwable t) {
                log.error("Error processing Info object during housekeeping: ", t);
            } finally {
                s.release();
            }
        }
        // if we have expired objects which are not dead then prepare them for housekeeping
        for (final String expiredInfoId : expiredNotDead) {
            try {
                T expiredInfo = get(expiredInfoId);
                String beanName = expiredInfo.getSimpleSipBeanId();
                log.info(String.format("Housekeeping: preparing an info %s for being housekept by %s",
                        expiredInfoId, beanName));
                HousekeeperAware creatorBean = (HousekeeperAware) applicationContext.getBean(beanName);
                creatorBean.killHousekeeperCandidate(expiredInfoId);
            } catch (Throwable t) {
                log.error(String.format(
                        "Unable to kill housekeeper candidate %s...will still remove from collection next housekeep",
                        expiredInfoId), t);
            } finally {
                //force housekeeping next time for that object
                ConcurrentUpdateBlock concurrentUpdateBlock = new ConcurrentUpdateBlock() {
                    public void execute() {
                        log.info(String.format("Housekeeping: setting housekeepForced flag to true in info %s",
                                expiredInfoId));
                        T info = get(expiredInfoId);
                        info.setHousekeepForced(true);
                        replace(info);
                    }

                    public String getResourceId() {
                        return expiredInfoId;
                    }
                };
                concurrentUpdateManager.executeConcurrentUpdate(concurrentUpdateBlock);
            }
        }
    } catch (Throwable t) {
        log.error("Error processing timer callback", t);
    }
}

From source file:org.openhab.io.mqttembeddedbroker.internal.MqttEmbeddedBrokerServiceTest.java

public void waitForConnectionChange(MqttBrokerConnection c, MqttConnectionState expectedState)
        throws InterruptedException {
    Semaphore semaphore = new Semaphore(1);
    semaphore.acquire();

    MqttConnectionObserver mqttConnectionObserver = (state, error) -> {
        if (state == expectedState) {
            semaphore.release();/*from   www  .  j  a v a2s .  c o  m*/
        }
    };
    c.addConnectionObserver(mqttConnectionObserver);
    if (c.connectionState() == expectedState) {
        semaphore.release();
    }

    // Start the connection and wait until timeout or connected callback returns.
    semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS);

    c.removeConnectionObserver(mqttConnectionObserver);

}

From source file:com.bt.aloha.collections.memory.InMemoryCollectionImpl.java

public void remove(String infoId) {
    Semaphore semaphore = getSemaphores().get(infoId);
    if (semaphore == null)
        return;/* www.j  av a 2  s  .  c o  m*/

    try {
        semaphore.acquire();
    } catch (InterruptedException e) {
        log.error(String.format(FAILED_TO_REMOVE_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(),
                e.getMessage()));
        throw new CollectionAccessInterruptedException(String.format(FAILED_TO_REMOVE_OBJECT_MESSAGE, infoId,
                this.getClass().getSimpleName(), e.getMessage()), e);
    }
    try {
        if (infos.remove(infoId) != null) {
            getSemaphores().remove(infoId);
            log.info(String.format("Removed info %s", infoId));
        } else
            log.warn(String.format("Failed to find info %s", infoId));
    } finally {
        semaphore.release();
    }
}