Example usage for com.google.common.collect Sets newConcurrentHashSet

List of usage examples for com.google.common.collect Sets newConcurrentHashSet

Introduction

In this page you can find the example usage for com.google.common.collect Sets newConcurrentHashSet.

Prototype

public static <E> Set<E> newConcurrentHashSet() 

Source Link

Document

Creates a thread-safe set backed by a hash map.

Usage

From source file:com.facebook.buck.features.project.intellij.IjProject.java

/**
 * Perform the write to disk.//w  w w. ja  va  2s. co m
 *
 * @param updateOnly whether to write all modules in the graph to disk, or only the ones which
 *     correspond to the listed targets
 * @return set of {@link BuildTarget}s which should be built in order for the project to index
 *     correctly.
 * @throws IOException
 */
private ImmutableSet<BuildTarget> performWriteOrUpdate(boolean updateOnly) throws IOException {
    final Set<BuildTarget> requiredBuildTargets = Sets.newConcurrentHashSet();
    IjLibraryFactory libraryFactory = new DefaultIjLibraryFactory(new DefaultIjLibraryFactoryResolver(
            projectFilesystem, sourcePathResolver, graphBuilder, ruleFinder, requiredBuildTargets));
    IjModuleFactoryResolver moduleFactoryResolver = new DefaultIjModuleFactoryResolver(graphBuilder,
            sourcePathResolver, ruleFinder, projectFilesystem, requiredBuildTargets);
    SupportedTargetTypeRegistry typeRegistry = new SupportedTargetTypeRegistry(projectFilesystem,
            moduleFactoryResolver, projectConfig, javaPackageFinder);
    AndroidManifestParser androidManifestParser = new AndroidManifestParser(projectFilesystem);
    IjModuleGraph moduleGraph = IjModuleGraphFactory.from(projectFilesystem, projectConfig,
            targetGraphAndTargets.getTargetGraph(), libraryFactory,
            new DefaultIjModuleFactory(projectFilesystem, typeRegistry),
            new DefaultAggregationModuleFactory(typeRegistry));
    JavaPackageFinder parsingJavaPackageFinder = ParsingJavaPackageFinder.preparse(javaFileParser,
            projectFilesystem, IjProjectTemplateDataPreparer.createPackageLookupPathSet(moduleGraph),
            javaPackageFinder);
    IjProjectTemplateDataPreparer templateDataPreparer = new IjProjectTemplateDataPreparer(
            parsingJavaPackageFinder, moduleGraph, projectFilesystem, projectConfig, androidManifestParser);
    IntellijModulesListParser modulesParser = new IntellijModulesListParser();
    IjProjectWriter writer = new IjProjectWriter(targetGraphAndTargets.getTargetGraph(), templateDataPreparer,
            projectConfig, projectFilesystem, modulesParser, cleaner, outFilesystem);

    if (updateOnly) {
        writer.update();
    } else {
        writer.write();
    }
    PregeneratedCodeWriter pregeneratedCodeWriter = new PregeneratedCodeWriter(templateDataPreparer,
            projectConfig, outFilesystem, androidManifestParser, cleaner);
    pregeneratedCodeWriter.write();

    if (projectConfig.getGeneratedFilesListFilename().isPresent()) {
        cleaner.writeFilesToKeepToFile(projectConfig.getGeneratedFilesListFilename().get());
    }

    return ImmutableSet.copyOf(requiredBuildTargets);
}

From source file:com.google.devtools.build.skyframe.DirtyTrackingProgressReceiver.java

/** Returns the set of all keys that are enqueued for evaluation, and resets the set to empty. */
protected Set<SkyKey> getAndClearInflightKeys() {
    Set<SkyKey> keys = inflightKeys;
    inflightKeys = Sets.newConcurrentHashSet();
    return keys;/*from   w w w . jav a  2s .  com*/
}

From source file:org.lanternpowered.server.text.translation.LanternTranslationManager.java

private void loadAssetBundle(Asset asset, Locale locale, boolean refresh) {
    try {//from   w  ww .ja v  a  2  s.  c o  m
        final InputStream inputStream = asset.getUrl().openStream();
        try {
            final ResourceBundle bundle = new PropertyResourceBundle(inputStream);
            this.bundles.computeIfAbsent(locale, locale0 -> Sets.newConcurrentHashSet()).add(bundle);
            if (refresh) {
                final Set<ResourceKey> refreshKeys = Sets.newHashSet();
                for (ResourceKey key : this.resourceBundlesCache.asMap().keySet()) {
                    Locale locale1 = key.locale == null ? Locale.ENGLISH : key.locale;
                    if (locale1.equals(locale) && bundle.containsKey(key.name)) {
                        refreshKeys.add(key);
                    }
                }
                if (!refreshKeys.isEmpty()) {
                    this.resourceBundlesCache.invalidateAll(refreshKeys);
                }
            }
        } catch (IOException e) {
            Lantern.getLogger().warn("Unable to create the resource bundle for: " + asset.getId(), e);
        }
    } catch (IOException e) {
        Lantern.getLogger().warn("Unable to open the asset stream for: " + asset.getId(), e);
    }
}

From source file:com.quancheng.saluki.registry.consul.ConsulRegistry.java

@Override
protected synchronized void doSubscribe(GrpcURL url, NotifyListener.NotifyServiceListener listener) {
    Pair<GrpcURL, Set<NotifyListener.NotifyServiceListener>> listenersPair = notifyServiceListeners
            .get(url.getServiceKey());/* w w  w  .  j av  a2 s  . c o m*/
    if (listenersPair == null) {
        Set<NotifyListener.NotifyServiceListener> listeners = Sets.newConcurrentHashSet();
        listeners.add(listener);
        listenersPair = new ImmutablePair<GrpcURL, Set<NotifyListener.NotifyServiceListener>>(url, listeners);
    } else {
        listenersPair.getValue().add(listener);
    }
    notifyServiceListeners.putIfAbsent(url.getServiceKey(), listenersPair);
    if (!serviceGroupLookUped.contains(url.getGroup())) {
        serviceGroupLookUped.add(url.getGroup());
        ServiceLookUper serviceLookUper = new ServiceLookUper(url.getGroup());
        serviceLookUper.setDaemon(true);
        serviceLookUper.start();
        ConsulEphemralNode ephemralNode = this.buildEphemralNode(url, ThrallRoleType.CONSUMER);
        client.registerEphemralNode(ephemralNode);
    } else {
        notifyListener(url, listener);
    }
}

From source file:com.google.gerrit.lucene.SubIndex.java

SubIndex(Directory dir, final String dirName, GerritIndexWriterConfig writerConfig,
        SearcherFactory searcherFactory) throws IOException {
    this.dir = dir;
    IndexWriter delegateWriter;//from  ww  w  . j a v  a  2s .  c om
    long commitPeriod = writerConfig.getCommitWithinMs();

    if (commitPeriod < 0) {
        delegateWriter = new AutoCommitWriter(dir, writerConfig.getLuceneConfig());
    } else if (commitPeriod == 0) {
        delegateWriter = new AutoCommitWriter(dir, writerConfig.getLuceneConfig(), true);
    } else {
        final AutoCommitWriter autoCommitWriter = new AutoCommitWriter(dir, writerConfig.getLuceneConfig());
        delegateWriter = autoCommitWriter;

        new ScheduledThreadPoolExecutor(1,
                new ThreadFactoryBuilder().setNameFormat("Commit-%d " + dirName).setDaemon(true).build())
                        .scheduleAtFixedRate(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (autoCommitWriter.hasUncommittedChanges()) {
                                        autoCommitWriter.manualFlush();
                                        autoCommitWriter.commit();
                                    }
                                } catch (IOException e) {
                                    log.error("Error committing Lucene index " + dirName, e);
                                } catch (OutOfMemoryError e) {
                                    log.error("Error committing Lucene index " + dirName, e);
                                    try {
                                        autoCommitWriter.close();
                                    } catch (IOException e2) {
                                        log.error("SEVERE: Error closing Lucene index " + dirName
                                                + " after OOM; index may be corrupted.", e);
                                    }
                                }
                            }
                        }, commitPeriod, commitPeriod, MILLISECONDS);
    }
    writer = new TrackingIndexWriter(delegateWriter);
    searcherManager = new WrappableSearcherManager(writer.getIndexWriter(), true, searcherFactory);

    notDoneNrtFutures = Sets.newConcurrentHashSet();

    reopenThread = new ControlledRealTimeReopenThread<>(writer, searcherManager,
            0.500 /* maximum stale age (seconds) */, 0.010 /* minimum stale age (seconds) */);
    reopenThread.setName("NRT " + dirName);
    reopenThread.setPriority(Math.min(Thread.currentThread().getPriority() + 2, Thread.MAX_PRIORITY));
    reopenThread.setDaemon(true);

    // This must be added after the reopen thread is created. The reopen thread
    // adds its own listener which copies its internally last-refreshed
    // generation to the searching generation. removeIfDone() depends on the
    // searching generation being up to date when calling
    // reopenThread.waitForGeneration(gen, 0), therefore the reopen thread's
    // internal listener needs to be called first.
    // TODO(dborowitz): This may have been fixed by
    // http://issues.apache.org/jira/browse/LUCENE-5461
    searcherManager.addListener(new RefreshListener() {
        @Override
        public void beforeRefresh() throws IOException {
        }

        @Override
        public void afterRefresh(boolean didRefresh) throws IOException {
            for (NrtFuture f : notDoneNrtFutures) {
                f.removeIfDone();
            }
        }
    });

    reopenThread.start();
}

From source file:org.apache.gobblin.metrics.MetricContext.java

protected MetricContext(String name, MetricContext parent, List<Tag<?>> tags, boolean isRoot)
        throws NameConflictException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(name));

    this.closer = Closer.create();

    try {/* www .j ava  2s.c o m*/
        this.innerMetricContext = this.closer.register(new InnerMetricContext(this, name, parent, tags));
    } catch (ExecutionException ee) {
        throw Throwables.propagate(ee);
    }

    this.contextAwareMetricsSet = Sets.newConcurrentHashSet();

    this.notificationTargets = Maps.newConcurrentMap();
    this.executorServiceOptional = Optional.absent();

    this.notificationTimer = new ContextAwareTimer(this, GOBBLIN_METRICS_NOTIFICATIONS_TIMER_NAME);
    register(this.notificationTimer);

    if (!isRoot) {
        RootMetricContext.get().addMetricContext(this);
    }
}

From source file:org.restcomm.media.control.mgcp.endpoint.GenericMgcpEndpoint.java

public GenericMgcpEndpoint(EndpointIdentifier endpointId, MgcpConnectionProvider connectionProvider,
        MediaGroup mediaGroup) {/*from   w  ww .  j  a v  a  2 s  .  co m*/
    // MGCP Components
    this.connectionProvider = connectionProvider;

    // Endpoint Properties
    this.endpointId = endpointId;
    this.connections = new ConcurrentHashMap<>(5);

    // Endpoint State
    this.active = new AtomicBoolean(false);

    // Media Components
    this.mediaGroup = mediaGroup;

    // Events and Signals
    this.notifiedEntity = new NotifiedEntity();
    this.signals = new ConcurrentHashMap<>(5);
    this.requestedEndpointEvents = EMPTY_ENDPOINT_EVENTS;
    this.requestedConnectionEvents = Multimaps
            .synchronizedSetMultimap(HashMultimap.<Integer, MgcpRequestedEvent>create());

    // Observers
    this.endpointObservers = Sets.newConcurrentHashSet();
    this.messageObservers = Sets.newConcurrentHashSet();
}

From source file:com.quancheng.saluki.core.registry.internal.AbstractRegistry.java

public void subscribe(GrpcURL url, NotifyListener.NotifyServiceListener listener) {
    if (url == null) {
        throw new IllegalArgumentException("subscribe url == null");
    }//from  w ww. j a  v a  2 s .  co m
    if (listener == null) {
        throw new IllegalArgumentException("subscribe listener == null");
    }
    String[] keys = new String[] { Constants.ASYNC_KEY, Constants.GENERIC_KEY, Constants.TIMEOUT };
    url = url.removeParameters(keys);
    if (logger.isInfoEnabled()) {
        logger.info("Subscribe: " + url);
    }
    Set<NotifyListener.NotifyServiceListener> listeners = subscribed.get(url);
    if (listeners == null) {
        subscribed.putIfAbsent(url, Sets.newConcurrentHashSet());
        listeners = subscribed.get(url);
    }
    listeners.add(listener);
}

From source file:org.attribyte.relay.FilesSupplier.java

/**
 * Creates a files supplier.//from   www .ja v  a2  s. co  m
 * @param sourceDir The source directory.
 * @param recurseSourceDirs Should subdirectories be searched?
 * @param completedMessageDir The optional (sub)directory where completed messages are moved.
 * @param lostMessageDir The (sub)directory where lost messages are moved.
 * @param continuous Does the supplier run continuously - monitoring the source directory for new files?
 * @param continuousReloadPauseMillis The number of milliseconds to pause between checks for new files when running continuously.
 * @param initialState The initial state, if any.
 * @param saveStateInterval The number of messages between state saves.
 * @param logger The logger. If <code>null</code>, messages are logged to the console.
 * @throws IOException on create error such as a filesystem error.
 */
public FilesSupplier(final File sourceDir, final boolean recurseSourceDirs,
        final Optional<String> completedMessageDir, final String lostMessageDir, final boolean continuous,
        final int continuousReloadPauseMillis, final Optional<ByteString> initialState,
        final int saveStateInterval, final Logger logger) throws IOException {
    this.rootDir = sourceDir;
    this.completedMessageDir = completedMessageDir;
    this.lostMessageDir = lostMessageDir;
    this.continuous = continuous;
    this.continuousReloadPauseMillis = continuousReloadPauseMillis;
    this.saveStateInterval = saveStateInterval;
    this.logger = logger != null ? logger : new ConsoleLogger();
    this.processedSet = Sets.newConcurrentHashSet();
    if (initialState.isPresent()) {
        deserializeState(initialState.get());
    }
    this.processedSetFilter = pathname -> pathname.isFile() && pathname.canRead()
            && !processedSet.contains(pathname.getAbsolutePath());
    this.recurseSourceDirs = recurseSourceDirs;
    if (recurseSourceDirs) {
        recurseSourceDirs();
    } else {
        sourceDirs = ImmutableList.of(rootDir).iterator();
    }
    createIterator();
    state = State.MESSAGE;
}

From source file:org.opennms.netmgt.bsm.service.model.graph.internal.GraphAlgorithms.java

/**
 * Generates the set of all possible subsets from the
 * given elements./*from w ww. j  av  a  2s  .co m*/
 *
 * @param elements S
 * @return P(S)
 */
protected static <T> Set<Set<T>> generatePowerSet(Collection<T> elements) {
    Set<Set<T>> powerSet = Sets.newConcurrentHashSet(); // Allows us to modify while iterating
    powerSet.add(Sets.newHashSet());
    for (T element : elements) {
        Iterator<Set<T>> iterator = powerSet.iterator();
        while (iterator.hasNext()) {
            Set<T> existingSubset = iterator.next();
            Set<T> newSubset = Sets.newHashSet(existingSubset);
            newSubset.add(element);
            powerSet.add(newSubset);
        }
    }
    return powerSet;
}