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, boolean fair) 

Source Link

Document

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

Usage

From source file:org.mrgeo.services.wms.WmsGenerator.java

public WmsGenerator() throws NumberFormatException {
    super();/*w  ww.  j  a  va 2 s.  com*/
    if (semaphore == null) {
        semaphore = new Semaphore(Integer.parseInt(
                MrGeoProperties.getInstance().getProperty("org.mrgeo.services.WmsGenerator.permits", "3")),
                true);
    }
}

From source file:org.apache.hadoop.hdfs.qjournal.client.HttpImageUploadChannel.java

public HttpImageUploadChannel(String uri, String journalId, NamespaceInfo nsinfo, long txid, long epoch,
        int maxBufferedChunks) {
    this.uri = uri;
    this.journalId = journalId;
    this.namespaceInfoString = nsinfo.toColonSeparatedString();
    this.txid = txid;
    this.epoch = epoch;
    this.maxBufferedChunks = maxBufferedChunks;
    this.available = new Semaphore(maxBufferedChunks, true);

    sendExecutor = Executors.newSingleThreadExecutor();
}

From source file:org.apache.pulsar.proxy.server.ProxyService.java

public ProxyService(ProxyConfiguration proxyConfig, AuthenticationService authenticationService)
        throws IOException {
    checkNotNull(proxyConfig);/*from   w  w w . j  a  v a2 s.  c  o m*/
    this.proxyConfig = proxyConfig;

    this.lookupRequestSemaphore = new AtomicReference<Semaphore>(
            new Semaphore(proxyConfig.getMaxConcurrentLookupRequests(), false));

    String hostname;
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
    if (proxyConfig.getServicePort().isPresent()) {
        this.serviceUrl = String.format("pulsar://%s:%d/", hostname, proxyConfig.getServicePort().get());
    } else {
        this.serviceUrl = null;
    }

    if (proxyConfig.getServicePortTls().isPresent()) {
        this.serviceUrlTls = String.format("pulsar://%s:%d/", hostname, proxyConfig.getServicePortTls().get());
    } else {
        this.serviceUrlTls = null;
    }

    this.acceptorGroup = EventLoopUtil.newEventLoopGroup(1, acceptorThreadFactory);
    this.workerGroup = EventLoopUtil.newEventLoopGroup(numThreads, workersThreadFactory);
    this.authenticationService = authenticationService;
}

From source file:edu.chalmers.dat076.moviefinder.service.MovieFileDatabaseHandlerImpl.java

@Override
public void saveFile(final Path path) {
    Runnable r = new Runnable() {

        @Override//from w w w  .j a  v a2s.  c  om
        @Transactional
        public void run() {
            try {
                TemporaryMedia temporaryMedia = new TitleParser().parseMedia(path.getFileName().toString());
                TraktResponse traktData = new TraktHandler().getByTmpMedia(temporaryMedia);
                if (traktData != null) {
                    if (traktData instanceof TraktMovieResponse) {
                        Movie movie = new Movie(path.toString(), traktData);
                        try {
                            try {
                                movieSemaphore.acquire();
                            } catch (InterruptedException ex) {
                            }
                            movieRepository.save(movie);
                        } catch (DataIntegrityViolationException e) {
                        } finally {
                            movieSemaphore.release();
                        }
                    } else {
                        TraktEpisodeResponse epr = (TraktEpisodeResponse) traktData;
                        Semaphore sLock = serieLock.get(epr.getShow().getTitle());
                        if (sLock == null) {
                            sLock = new Semaphore(1, true);
                            serieLock.put(epr.getShow().getTitle(), sLock);
                        }
                        try {
                            sLock.acquire();
                            Series s = seriesRepository.findByImdbId(epr.getShow().getImdbId());
                            if (s == null) {
                                TraktShowResponse sr = new TraktHandler()
                                        .getByShowName(temporaryMedia.getName());
                                if (sr != null) {
                                    s = new Series(sr);
                                    seriesRepository.save(s);
                                }
                            }

                            if (s != null) {
                                Episode ep = new Episode(path.toString(), traktData, s);
                                episodeRepository.save(ep);
                            }
                        } catch (InterruptedException ex) {
                        } finally {
                            sLock.release();
                        }

                    }
                }
            } finally {
                lock.release();
            }
        }

    };

    try {
        lock.acquire();
    } catch (InterruptedException ex) {
    }

    new Thread(r).start();
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

public VideoThumbnailPlugin(final BundleContext bundleContext) throws IOException {
    final String bundledFFmpegBinaryPath = getBundledFFmpegBinaryPath();
    final String ffmpegBinaryName = StringUtils.substringAfterLast(bundledFFmpegBinaryPath, "/");
    final String ffmpegFolderPath = FilenameUtils.concat(System.getProperty("ddf.home"),
            "bin_third_party/ffmpeg");
    ffmpegPath = FilenameUtils.concat(ffmpegFolderPath, ffmpegBinaryName);

    try (final InputStream inputStream = bundleContext.getBundle().getEntry(bundledFFmpegBinaryPath)
            .openStream()) {//w ww.  j  a  v  a  2  s.com
        copyFFmpegBinary(inputStream);
    }

    limitFFmpegProcessesSemaphore = new Semaphore(MAX_FFMPEG_PROCESSES, true);
}

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

public void add(T info) {
    if (info == null)
        throw new IllegalArgumentException(String.format(
                "Trying to add element in collection %s with null info", this.getClass().getSimpleName()));

    String infoId = info.getId();
    log.debug("infoId: " + infoId);
    if (getSemaphores().containsKey(infoId))
        throw new IllegalArgumentException(
                String.format("Info %s already exists in collection %s, use replaceDialog instead", infoId,
                        this.getClass().getSimpleName()));

    infos.put(infoId, (T) info.cloneObject());
    getSemaphores().put(infoId, new Semaphore(1, true));
    log.debug(String.format("Added info %s to %s", info.getId(), this.getClass().getSimpleName()));
}

From source file:io.mandrel.requests.http.ApacheHttpRequester.java

public void init() {

    available = new Semaphore(maxParallel(), true);

    SSLContext sslContext = SSLContexts.createSystemDefault();
    HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();

    Registry<ConnectionSocketFactory> sessionStrategyRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override//  w w w .  j a  va 2  s . c  o  m
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("localhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return new InetAddress[] { nameResolver().resolve(host) };
            }
        }
    };

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            sessionStrategyRegistry, dnsResolver);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(maxHeaderCount)
            .setMaxLineLength(maxLineLength).build();

    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(maxPersistentConnections());
    connManager.setDefaultMaxPerRoute(maxPersistentConnections());

    // TODO
    // Use custom credentials provider if necessary.
    // CredentialsProvider credentialsProvider = new
    // BasicCredentialsProvider();

    // Create global request configuration
    defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setMaxRedirects(maxRedirects())
            .setSocketTimeout(socketTimeout()).setConnectTimeout(connectTimeout())
            .setConnectionRequestTimeout(requestTimeOut()).setRedirectsEnabled(followRedirects()).build();

    // Create an HttpClient with the given custom dependencies and
    // configuration.
    client = HttpClients.custom().setConnectionManager(connManager)
            // .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(defaultRequestConfig).build();
}

From source file:voldemort.store.routed.ThreadPoolRoutedStore.java

@Override
public boolean delete(final ByteArray key, final Version version) throws VoldemortException {
    StoreUtils.assertValidKey(key);/*from   w ww  .  j  a va2  s  .  c o  m*/
    final List<Node> nodes = availableNodes(routingStrategy.routeRequest(key.get()));

    // quickly fail if there aren't enough live nodes to meet the
    // requirements
    final int numNodes = nodes.size();
    if (numNodes < this.storeDef.getRequiredWrites())
        throw new InsufficientOperationalNodesException("Only " + numNodes + " nodes in preference list, but "
                + this.storeDef.getRequiredWrites() + " writes required.");

    // A count of the number of successful operations
    final AtomicInteger successes = new AtomicInteger(0);
    final AtomicBoolean deletedSomething = new AtomicBoolean(false);
    // A list of thrown exceptions, indicating the number of failures
    final List<Exception> failures = Collections.synchronizedList(new LinkedList<Exception>());

    // A semaphore indicating the number of completed operations
    // Once inititialized all permits are acquired, after that
    // permits are released when an operation is completed.
    // semaphore.acquire(n) waits for n operations to complete
    final Semaphore semaphore = new Semaphore(0, false);
    // Add the operations to the pool
    for (final Node node : nodes) {
        this.executor.execute(new Runnable() {

            @Override
            public void run() {
                long startNs = System.nanoTime();
                try {
                    boolean deleted = innerStores.get(node.getId()).delete(key, version);
                    successes.incrementAndGet();
                    deletedSomething.compareAndSet(false, deleted);
                    recordSuccess(node, startNs);
                } catch (UnreachableStoreException e) {
                    failures.add(e);
                    recordException(node, startNs, e);
                } catch (VoldemortApplicationException e) {
                    throw e;
                } catch (Exception e) {
                    failures.add(e);
                    logger.warn("Error in DELETE on node " + node.getId() + "(" + node.getHost() + ")", e);
                } finally {
                    // signal that the operation is complete
                    semaphore.release();
                }
            }
        });
    }

    int attempts = Math.min(storeDef.getPreferredWrites(), numNodes);
    if (this.storeDef.getPreferredWrites() <= 0) {
        return true;
    } else {
        for (int i = 0; i < numNodes; i++) {
            try {
                long timeoutMs = timeoutConfig.getOperationTimeout(VoldemortOpCode.DELETE_OP_CODE);
                boolean acquired = semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS);
                if (!acquired)
                    logger.warn("Delete operation timed out waiting for operation " + i
                            + " to complete after waiting " + timeoutMs + " ms.");
                // okay, at least the required number of operations have
                // completed, were they successful?
                if (successes.get() >= attempts)
                    return deletedSomething.get();
            } catch (InterruptedException e) {
                throw new InsufficientOperationalNodesException("Delete operation interrupted!", e);
            }
        }
    }

    // If we get to here, that means we couldn't hit the preferred number
    // of writes, throw an exception if you can't even hit the required
    // number
    if (successes.get() < storeDef.getRequiredWrites())
        throw new InsufficientOperationalNodesException(
                this.storeDef.getRequiredWrites() + " deletes required, but " + successes.get() + " succeeded.",
                failures);
    else
        return deletedSomething.get();
}

From source file:com.bt.sdk.callcontrol.sip.util.EhCacheCollectionImpl.java

@SuppressWarnings("unchecked")
public void add(T info) {
    if (info == null)
        throw new IllegalArgumentException(String.format(
                "Trying to add element in collection %s with null info", this.getClass().getSimpleName()));

    String infoId = info.getId();
    if (semaphoreCache.getKeys().contains(infoId))
        throw new IllegalArgumentException(
                String.format("Info %s already exists in collection %s, use replaceDialog instead", infoId,
                        this.getClass().getSimpleName()));

    //infos.put(infoId, (T)info.cloneObject());
    cache.put(new Element(infoId, info.cloneObject()));
    cache.flush();/*from   ww  w  .  jav a2 s  .  c  o  m*/
    semaphoreCache.put(new Element(infoId, new Semaphore(1, true)));
    semaphoreCache.flush();
    log.debug(String.format("Added info %s to %s", info.getId(), this.getClass().getSimpleName()));
}