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.synapse.debug.SynapseDebugManager.java

protected SynapseDebugManager() {
    mediationFlowLock = new ReentrantLock();
    mediationFlowSem = new Semaphore(0);
    addedPropertyValuesMap = new HashMap<MessageContext, Map<String, Set<String>>>();
}

From source file:com.miraclelinux.historygluon.HistoryStreamer.java

private HistoryStreamer() {
    m_log = LogFactory.getLog(HistoryStreamer.class);
    m_queue = new LinkedBlockingQueue<HistoryStreamElement>();
    m_semaphore = new Semaphore(1);
    m_semaphore.acquireUninterruptibly(); // This is never blocked.
    m_working_sem = new Semaphore(1);
}

From source file:org.commoncrawl.service.parser.client.ParserNode.java

public ParseResult dispatchRequest(final ParseRequest request) throws IOException {
    final AtomicReference<ParseResult> result = new AtomicReference<ParseResult>();

    if (_online.get()) {
        //      LOG.info("Dispatching Parse Request for URL:" + request.getDocURL() 
        //          + " to Node:" + _nodeName);  
        final Semaphore requestSemaphore = new Semaphore(0);

        _eventLoop.queueAsyncCallback(new org.commoncrawl.async.Callback() {

            @Override/*from w ww.ja v a  2  s . co  m*/
            public void execute() {
                try {
                    _asyncStub.parseDocument(request, new Callback<ParseRequest, ParseResult>() {

                        @Override
                        public void requestComplete(AsyncRequest<ParseRequest, ParseResult> request) {
                            try {
                                //                  LOG.info("Parse Request for URL:" + request.getInput().getDocURL() 
                                //                      + " recvd responseStatus:" + request.getStatus() 
                                //                      + " from Node:" + _nodeName); 

                                if (request.getStatus() == Status.Success) {
                                    result.set(request.getOutput());
                                }
                            } finally {
                                //                  LOG.info("Releasing Request Semaphore for URL:" + request.getInput().getDocURL());
                                requestSemaphore.release();
                            }
                        }
                    });
                } catch (Exception e) {
                    LOG.error(CCStringUtils.stringifyException(e));
                    LOG.info("Releasing Request Semaphore for URL:" + request.getDocURL());
                    requestSemaphore.release();
                }
            }
        });

        //      LOG.info("Waiting on ParseReq Semaphore for URL:"+ request.getDocURL());
        requestSemaphore.acquireUninterruptibly();
        //      LOG.info("ParseReq Semaphore signlaed for URL:"+ request.getDocURL());
    }
    return result.get();
}

From source file:org.paxle.core.threading.impl.Master.java

public void process(final Data cmd) throws Exception {
    // creating and assigning a dummy output queues
    final Semaphore s = new Semaphore(0);
    final IInputQueue<Data> inputQueue = new IInputQueue<Data>() {
        private int counter = 0;

        public Data dequeue() throws InterruptedException {
            if (counter > 0)
                throw new IllegalStateException("Method executed multiple times");
            this.counter++;
            return cmd;
        }/*ww  w .j  ava 2  s.c om*/

        public void waitForNext() throws InterruptedException {
            throw new IllegalStateException("You are not allowed to call this method");
        }
    };
    final IOutputQueue<Data> outputQueue = new IOutputQueue<Data>() {
        public void enqueue(Data command) throws InterruptedException {
            s.release();
        }
    };

    // process the command
    this.process(inputQueue, outputQueue, false);

    // waiting for the worker to finish execution
    s.acquire();
}

From source file:com.thoughtworks.studios.shine.cruise.stage.details.LazyStageGraphLoaderTest.java

@Test
public void shouldReuseTransformerAcrossSerialInvocations() {
    StageIdentifier stageId = new StageIdentifier("pipeline-foo", 23, "stage-1", "1");

    DummyStageResourceImporter realLoader = new DummyStageResourceImporter(realGraph(), stageId,
            new Semaphore(2));

    LazyStageGraphLoader loader = new LazyStageGraphLoader(realLoader, stageStorage, 1);

    loader.load(stageId);/*w w w. j av a 2s  .  c  om*/
    XSLTTransformerRegistry transformerRegistryFromFirstLoad = realLoader.transformerRegistry;

    stageStorage.clear();
    loader.load(stageId);
    XSLTTransformerRegistry transformerRegistryFromSecondLoad = realLoader.transformerRegistry;

    assertThat(transformerRegistryFromFirstLoad, sameInstance(transformerRegistryFromSecondLoad));
}

From source file:org.commoncrawl.util.shared.S3Downloader.java

public void shutdown() {

    if (_callback == null) {
        throw new RuntimeException("Invalid State - stop called on already inactive downloader");
    }//from w  w w.  j  a v  a 2  s.  co m

    _freezeDownloads = true;

    Thread eventThread = (_ownsEventLoop) ? _eventLoop.getEventThread() : null;

    final Semaphore shutdownSemaphore = new Semaphore(0);

    _eventLoop.setTimer(new Timer(1, false, new Timer.Callback() {

        // shutdown within the context of the async thread ... 
        public void timerFired(Timer timer) {

            try {

                // fail any active connections 
                for (NIOHttpConnection connection : Lists.newArrayList(_activeConnections)) {
                    S3DownloadItem item = (S3DownloadItem) connection.getContext();
                    if (item != null) {
                        failDownload(item, NIOHttpConnection.ErrorType.UNKNOWN, connection, false);
                    }
                }

                _activeConnections.clear();

                // next, fail all queued items 
                for (S3DownloadItem item : _queuedItems) {
                    failDownload(item, NIOHttpConnection.ErrorType.UNKNOWN, null, false);
                }
                _queuedItems.clear();
                _freezeDownloads = false;
                _callback = null;

                if (_ownsEventLoop) {
                    //System.out.println("Stopping Event Loop");
                    _eventLoop.stop();
                }
                _eventLoop = null;
                _ownsEventLoop = false;
            } finally {
                //System.out.println("Releasing Semaphore");
                shutdownSemaphore.release();
            }
        }
    }));
    //System.out.println("Acquiring Shutdown Semaphore");
    shutdownSemaphore.acquireUninterruptibly();
    //System.out.println("Acquired Shutdown Semaphore");

    try {

        if (eventThread != null) {
            eventThread.join();
        }
    } catch (InterruptedException e) {
    }
}

From source file:org.commoncrawl.service.parser.server.ParserSlaveServer.java

@Override
protected boolean startDaemons() {
    _parserThreads = new Thread[thread_count];
    _threadSemaphore = new Semaphore(-(thread_count - 1));
    for (int i = 0; i < thread_count; ++i) {
        _parserThreads[i] = new Thread(new Runnable() {

            @Override//from ww  w. jav  a 2  s.c o  m
            public void run() {

                try {
                    while (true) {
                        try {
                            final Request request = requestQueue.take();
                            if (request.requestContext == null) {
                                LOG.info("Parser Thread:" + Thread.currentThread().getId() + " Exiting.");
                                return;
                            } else {
                                ParseRequest parseRequest = request.requestContext.getInput();
                                ParseResult parseResult = request.requestContext.getOutput();

                                LOG.info("Parser Thread:" + Thread.currentThread().getId()
                                        + " got request for url:" + parseRequest.getDocURL());

                                try {

                                    _activeThreads.incrementAndGet();

                                    URL url = new URL(parseRequest.getDocURL());
                                    ParseWorker worker = new ParseWorker();
                                    worker.parseDocument(request.requestContext.getOutput(),
                                            parseRequest.getDomainId(), parseRequest.getDocId(), url,
                                            parseRequest.getDocHeaders(),
                                            new FlexBuffer(parseRequest.getDocContent().getReadOnlyBytes(),
                                                    parseRequest.getDocContent().getOffset(),
                                                    parseRequest.getDocContent().getCount()));

                                } catch (Exception e) {
                                    LOG.error(CCStringUtils.stringifyException(e));
                                    parseResult.setParseSuccessful(false);
                                    if (parseResult.getParseFailureReason().length() == 0) {
                                        parseResult.setParseFailureReason(CCStringUtils.stringifyException(e));
                                    }
                                } finally {
                                    _activeThreads.decrementAndGet();
                                }
                                getEventLoop().queueAsyncCallback(new Callback() {

                                    @Override
                                    public void execute() {
                                        try {
                                            request.requestContext.completeRequest();
                                        } catch (RPCException e) {
                                            LOG.error("RPC Exception when processing ParseRequest:"
                                                    + CCStringUtils.stringifyException(e));
                                        }
                                    }
                                });
                            }
                        } catch (InterruptedException e) {
                        }
                    }
                } finally {
                    _activeThreads.decrementAndGet();
                    _threadSemaphore.release();
                }
            }
        });
        _parserThreads[i].start();
    }
    return true;
}

From source file:org.apache.cayenne.datasource.UnmanagedPoolingDataSource.java

public UnmanagedPoolingDataSource(DataSource nonPoolingDataSource, PoolingDataSourceParameters parameters) {

    int minConnections = parameters.getMinConnections();
    int maxConnections = parameters.getMaxConnections();

    // sanity check
    if (minConnections < 0) {
        throw new IllegalArgumentException("Negative min connections: " + minConnections);
    }//from  ww  w . j  a va2  s . c  om

    if (maxConnections < 0) {
        throw new IllegalArgumentException("Negative max connections: " + maxConnections);
    }

    if (minConnections > maxConnections) {
        throw new IllegalArgumentException("Min connections (" + minConnections
                + ") is greater than max connections (" + maxConnections + ")");
    }

    this.nonPoolingDataSource = nonPoolingDataSource;
    this.maxQueueWaitTime = parameters.getMaxQueueWaitTime();
    this.validationQuery = parameters.getValidationQuery();
    this.minConnections = minConnections;
    this.maxConnections = maxConnections;
    this.pool = new ConcurrentHashMap<PoolAwareConnection, Object>((int) (maxConnections / 0.75));
    this.available = new ArrayBlockingQueue<PoolAwareConnection>(maxConnections);
    this.poolCap = new Semaphore(maxConnections);
    this.maxIdleConnections = maxIdleConnections(minConnections, maxConnections);

    // grow pool to min connections
    try {
        for (int i = 0; i < minConnections; i++) {
            PoolAwareConnection c = createUnchecked();
            reclaim(c);
        }
    } catch (BadValidationQueryException e) {
        throw new CayenneRuntimeException("Bad validation query: " + validationQuery, e);
    } catch (SQLException e) {
        LOGGER.info("Error creating new connection when starting connection pool, ignoring", e);
    }
}

From source file:cn.edu.wyu.documentviewer.RecentLoader.java

public RecentLoader(Context context, RootsCache roots, State state) {
    super(context);
    mRoots = roots;/*w w  w  . j av  a  2 s .  c o  m*/
    mState = state;

    // Keep clients around on high-RAM devices, since we'd be spinning them
    // up moments later to fetch thumbnails anyway.
    final ActivityManager am = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
    mQueryPermits = new Semaphore(
            am.isLowRamDevice() ? MAX_OUTSTANDING_RECENTS_SVELTE : MAX_OUTSTANDING_RECENTS);
}