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:com.bt.aloha.batchtest.v2.StackManagerSyncronizationSemaphoreImpl.java

public void initialize(int count, int max) {
    this.max = max;
    this.semaphore = new Semaphore(count);
    log.info("Initializing Syncronization semaphore to " + count);
}

From source file:edu.iu.harp.schstatic.StaticScheduler.java

@SuppressWarnings("unchecked")
public StaticScheduler(List<T> tasks) {
    threads = null;// w  ww  .j a v a2  s  .  c o  m
    barrier1 = new Semaphore(0);
    numTaskMonitors = tasks.size();
    taskMonitors = new TaskMonitor[numTaskMonitors];
    submitter = new Submitter<>(taskMonitors);
    int i = 0;
    for (T task : tasks) {
        taskMonitors[i] = new TaskMonitor<>(i, task, submitter, numTaskMonitors, barrier1);
        i++;
    }
}

From source file:edu.iu.harp.schdynamic.TaskMonitor.java

TaskMonitor(BlockingDeque<Input<I>> inQueue, BlockingQueue<Output<O>> outQueue, T task, Semaphore barrier1) {
    inputQueue = inQueue;/*from   w  w w. ja v a2s. c om*/
    outputQueue = outQueue;
    taskObject = task;
    this.barrier1 = barrier1;
    this.barrier2 = new Semaphore(0);
}

From source file:core.service.bus.socket.SocketWrapper.java

public SocketWrapper(Socket socket) {
    super();
    this.socket = socket;
    lock = new Semaphore(1);
}

From source file:frames.LoginFrame.java

public LoginFrame() {

    initComponents();//from w ww. ja  v  a2s . co  m

    //Enable calling the clients
    System.setSecurityManager(null);

    //Create semaphore with a single permission
    semaphore = new Semaphore(1);

    //Centralizes frame
    setLocationRelativeTo(null);

    //Make Login frame visible
    setVisible(true);
}

From source file:org.wso2.carbon.event.publisher.core.internal.BlockingEventQueue.java

public BlockingEventQueue(int maxSizeInMb, int maxNumOfEvents) {
    super(maxNumOfEvents);
    this.maxSizeInBytes = maxSizeInMb * 1000000;
    this.semaphore = new Semaphore(1);
    this.currentSize = new AtomicInteger(0);
    this.lock = new Object();
    this.currentEventSize = 0;
}

From source file:fr.aliasource.webmail.common.cache.FileCache.java

protected FileCache(IAccount account, String category, String cacheName, IDirectCommand<W> command) {
    super(account);
    this.command = command;
    updateLock = new Semaphore(1);
    this.category = category;
    this.cacheName = cacheName;
    this.cDirectory = account.getCache().getCachePath() + File.separator + category;
    new File(cDirectory).mkdirs();
    this.cFile = new File(cDirectory + File.separator + cacheName + ".xml");
    this.logger = LogFactory.getLog(getClass());

    if (!exists()) {
        initEmpty();/*from  w ww  . j  a  va  2 s .  co  m*/
    }
}

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

@Test
public void testAssignSingleTask() throws Exception {
    Semaphore idleWorkersSemaphore = new Semaphore(0);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(1));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, new TaskQueue() {
    });/* w w  w  .ja va  2  s  . c  o m*/
    workerPool.assignTask(getSleepIncrementTask());
    Thread.sleep(2000);
    Assert.assertEquals(1, SleepIncrementTask.executionCounter.intValue());
    workerPool.assignTask(getSleepIncrementTask());
    Thread.sleep(2000);
    Assert.assertEquals(2, SleepIncrementTask.executionCounter.intValue());
    Assert.assertEquals(2, idleWorkersSemaphore.availablePermits());
}

From source file:org.commoncrawl.service.queryserver.master.S3Helper.java

public static ArcFileItem retrieveArcFileItem(ArchiveInfo archiveInfo, EventLoop eventLoop) throws IOException {

    // the default bucket id 
    String bucketId = "commoncrawl-crawl-002";

    //ok, see if we need to switch buckets 
    if (archiveInfo.getCrawlNumber() == 1) {
        bucketId = "commoncrawl";
    }//from w  ww  . j a  v a  2  s.c o m

    S3Downloader downloader = new S3Downloader(bucketId, "", "", false);

    // now activate the segment log ... 
    final Semaphore downloadCompleteSemaphore = new Semaphore(0);
    final StreamingArcFileReader arcFileReader = new StreamingArcFileReader(false);
    //arcFileReader.setArcFileHasHeaderItemFlag(false);

    // create a buffer list we will append incoming content into ... 
    final LinkedList<ByteBuffer> bufferList = new LinkedList<ByteBuffer>();

    downloader.initialize(new S3Downloader.Callback() {

        @Override
        public boolean contentAvailable(int itemId, String itemKey, NIOBufferList contentBuffer) {
            LOG.info("ContentQuery contentAvailable called for Item:" + itemKey + " totalBytesAvailable:"
                    + contentBuffer.available());

            try {
                while (contentBuffer.available() != 0) {
                    bufferList.add(contentBuffer.read());
                }
                return true;
            } catch (IOException e) {
                LOG.error(CCStringUtils.stringifyException(e));
                return false;
            }
        }

        @Override
        public void downloadComplete(int itemId, String itemKey) {
            LOG.info("S3 Download Complete for item:" + itemKey);
            downloadCompleteSemaphore.release();
        }

        @Override
        public void downloadFailed(int itemId, String itemKey, String errorCode) {
            LOG.info("S3 Download Failed for item:" + itemKey);
            downloadCompleteSemaphore.release();
        }

        @Override
        public boolean downloadStarting(int itemId, String itemKey, int contentLength) {
            LOG.info("ContentQuery DownloadStarting for Item:" + itemKey + " contentLength:" + contentLength);
            return true;
        }

    }, eventLoop);

    LOG.info("Starting request for Item:"
            + hdfsNameToS3ArcFileName(archiveInfo.getArcfileDate(), archiveInfo.getArcfileIndex()) + " Offset:"
            + archiveInfo.getArcfileOffset());

    int sizeToRetrieve = (archiveInfo.getCompressedSize() != 0) ? archiveInfo.getCompressedSize() : 30000;
    sizeToRetrieve += 10;

    downloader.fetchPartialItem(
            hdfsNameToS3ArcFileName(archiveInfo.getArcfileDate(), archiveInfo.getArcfileIndex()),
            archiveInfo.getArcfileOffset() - 10, sizeToRetrieve);
    downloadCompleteSemaphore.acquireUninterruptibly();

    if (bufferList.size() == 0) {
        return null;
    }

    ByteBuffer firstBuffer = bufferList.getFirst();
    if (firstBuffer != null) {
        int offsetToGZIPHeader = scanForGZIPHeader(firstBuffer.duplicate());
        if (offsetToGZIPHeader != -1) {
            firstBuffer.position(offsetToGZIPHeader);
            LOG.info("*** Offset to GZIP Header:" + offsetToGZIPHeader);
        } else {
            LOG.error("*** Failed to find GZIP Header offset");
        }
    }

    // now try to decode content if possible
    for (ByteBuffer buffer : bufferList) {
        LOG.info("Adding Buffer of Size:" + buffer.remaining() + " Position:" + buffer.position() + " Limit:"
                + buffer.limit());
        arcFileReader.available(buffer);
    }

    ArcFileItem item = arcFileReader.getNextItem();

    if (item != null) {
        LOG.info("Request Returned item:" + item.getUri());
        LOG.info("Uncompressed Size:" + item.getContent().getCount());
    }
    return item;
}

From source file:org.wso2.carbon.event.receiver.core.internal.management.BlockingEventQueue.java

public BlockingEventQueue(int maxSizeInMb, int maxNumOfEvents) {
    this.maxSizeInBytes = maxSizeInMb * 1000000; // to convert to bytes
    this.queue = new LinkedBlockingQueue<>(maxNumOfEvents);
    this.semaphore = new Semaphore(1);
    this.currentSize = new AtomicInteger(0);
    this.lock = new Object();
    this.currentEventSize = 0;
}