Example usage for java.util.concurrent CopyOnWriteArraySet CopyOnWriteArraySet

List of usage examples for java.util.concurrent CopyOnWriteArraySet CopyOnWriteArraySet

Introduction

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

Prototype

public CopyOnWriteArraySet() 

Source Link

Document

Creates an empty set.

Usage

From source file:org.rifidi.edge.configuration.ConfigurationServiceImpl.java

@Override
public String createService(final String factoryID, final AttributeList attributes)
        throws CannotCreateServiceException {
    ServiceFactory<?> factory = factories.get(factoryID);
    if (factory == null) {
        logger.warn("Tried to use a nonexistent factory: " + factoryID);
        throw new CannotCreateServiceException();
    }//w  w w. j  a  v a2s  .com
    String serviceID = factoryID;
    serviceID = serviceID.replaceAll("[^A-Z^a-z^0-9^_]", "_") + "_";
    synchronized (serviceNames) {
        Integer counter = 1;
        String tempServiceID = serviceID + 1;
        // TODO: not nice but good enough for now
        while (serviceNames.contains(tempServiceID)) {
            counter++;
            tempServiceID = serviceID + counter;
        }
        serviceID = tempServiceID;
        serviceNames.add(serviceID);
    }

    DefaultConfigurationImpl config = createAndRegisterConfiguration(serviceID, factoryID, attributes,
            new HashSet<SessionDTO>());

    if (factoryToConfigurations.get(factoryID) == null) {
        factoryToConfigurations.put(factoryID, new CopyOnWriteArraySet<DefaultConfigurationImpl>());
    }
    factoryToConfigurations.get(factoryID).add(config);
    IDToConfigurations.put(serviceID, config);

    if (factory != null) {
        // TODO: Ticket #236
        try {
            factory.createInstance(serviceID);
            return serviceID;
        } catch (IllegalArgumentException e) {
            logger.error("exception", e);
        } catch (InvalidStateException e) {
            logger.error("exception ", e);
        }
    }
    throw new CannotCreateServiceException();
}

From source file:net.sf.logsaw.ui.impl.LogResourceManagerImpl.java

private synchronized void loadState() throws CoreException {
    logSet = new CopyOnWriteArraySet<ILogResource>();
    if (!stateFile.toFile().exists()) {
        // Not exists yet
        return;//from   www .ja  v a 2s. c  o m
    }
    IMemento rootElem = null;
    try {
        rootElem = XMLMemento.createReadRoot(new BufferedReader(
                new InputStreamReader(FileUtils.openInputStream(stateFile.toFile()), "UTF-8"))); //$NON-NLS-1$
    } catch (IOException e) {
        // Unexpected exception; wrap with CoreException
        throw new CoreException(new Status(IStatus.ERROR, UIPlugin.PLUGIN_ID,
                NLS.bind(Messages.LogResourceManager_error_failedToLoadState,
                        new Object[] { e.getLocalizedMessage() }),
                e));
    }
    // Check if we can read this
    Integer compat = rootElem.getInteger(ATTRIB_COMPAT);
    if ((compat == null) || (compat.intValue() != COMPAT_VERSION)) {
        throw new CoreException(new Status(IStatus.WARNING, UIPlugin.PLUGIN_ID,
                Messages.LogResourceManager_warn_stateFileIncompatible));
    }

    List<IStatus> statuses = new ArrayList<IStatus>();
    for (IMemento logElem : rootElem.getChildren(ELEM_LOG_RESOURCE)) {
        String name = null;
        try {
            name = logElem.getChild(ELEM_NAME).getTextData();
            IMemento dialectElem = logElem.getChild(ELEM_DIALECT);
            String dialectFactory = dialectElem.getString(ATTRIB_FACTORY);
            ILogDialectFactory factory = CorePlugin.getDefault().getLogDialectFactory(dialectFactory);
            ILogDialect dialect = factory.createLogDialect();

            // Restore config options of dialect
            loadConfigOptions(dialectElem, (IConfigurableObject) dialect.getAdapter(IConfigurableObject.class));
            String pk = logElem.getChild(ELEM_PK).getTextData();

            // TODO Dynamic factory for log resource
            ILogResource log = SimpleLogResourceFactory.getInstance().createLogResource();
            log.setDialect(dialect);
            log.setName(name);
            log.setPK(pk);

            // Restore config options of resource
            loadConfigOptions(logElem, (IConfigurableObject) log.getAdapter(IConfigurableObject.class));

            // Unlock if necessary
            if (IndexPlugin.getDefault().getIndexService().unlock(log)) {
                logger.warn("Unlocked log resource " + log.getName()); //$NON-NLS-1$
            }
            // Register log resource
            registerLogResource(log);
        } catch (Exception e) {
            statuses.add(new Status(IStatus.ERROR, UIPlugin.PLUGIN_ID, NLS.bind(
                    Messages.LogResourceManager_error_failedToRestoreLogResource, new Object[] { name }), e));
        }
    }
    if (!statuses.isEmpty()) {
        MultiStatus multiStatus = new MultiStatus(UIPlugin.PLUGIN_ID, 0,
                statuses.toArray(new IStatus[statuses.size()]),
                Messages.LogResourceManager_error_someLogResourcesCouldNotBeRestored, null);
        throw new CoreException(multiStatus);
    }
    logger.info("Loaded " + logSet.size() + " log resource(s)"); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:org.alfresco.repo.dictionary.DictionaryModelType.java

@SuppressWarnings("unchecked")
public void beforeDeleteNode(NodeRef nodeRef) {
    boolean workingCopy = nodeService.hasAspect(nodeRef, ContentModel.ASPECT_WORKING_COPY);
    NodeRef wcNodeRef = (NodeRef) AlfrescoTransactionSupport.getResource(KEY_WORKING_COPY);
    if ((wcNodeRef != null) && (wcNodeRef.equals(nodeRef))) {
        workingCopy = true;//from   w ww  .j av a  2 s  .com
    }

    boolean isVersionNode = nodeRef.getStoreRef().getIdentifier().equals(Version2Model.STORE_ID);

    // Ignore if the node is a working copy or version node
    if (!(workingCopy || isVersionNode)) {
        QName modelName = (QName) this.nodeService.getProperty(nodeRef, ContentModel.PROP_MODEL_NAME);

        if (logger.isTraceEnabled()) {
            logger.trace("beforeDeleteNode: nodeRef=" + nodeRef + " validate model delete (modelName="
                    + modelName + ")");
        }

        if (modelName != null) {
            // Validate model delete against usages - content and/or workflows
            if (!modelValidator.canDeleteModel(modelName)) {
                throw AlfrescoRuntimeException.create(MODEL_IN_USE, modelName);
            }

            Set<NodeRef> pendingModelDeletes = (Set<NodeRef>) AlfrescoTransactionSupport
                    .getResource(KEY_PENDING_DELETE_MODELS);
            if (pendingModelDeletes == null) {
                //pendingModelDeletes = Collections.newSetFromMap(new ConcurrentHashMap()); // Java 6
                pendingModelDeletes = new CopyOnWriteArraySet<NodeRef>();
                AlfrescoTransactionSupport.bindResource(KEY_PENDING_DELETE_MODELS, pendingModelDeletes);
            }
            pendingModelDeletes.add(tenantService.getName(nodeRef));

            AlfrescoTransactionSupport.bindListener(this.transactionListener);
        }
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("beforeDeleteNode: nodeRef=" + nodeRef + " ignored ("
                    + (workingCopy ? " workingCopy " : "") + (isVersionNode ? " isVersionNode " : "") + ") ["
                    + AlfrescoTransactionSupport.getTransactionId() + "]");
        }
    }
}

From source file:org.jiemamy.utils.collection.CollectionsUtil.java

/**
 * {@link CopyOnWriteArraySet}?????//from   w w w .j  a v  a  2 s  .co m
 * 
 * @param <E> {@link CopyOnWriteArraySet}??
 * @return {@link CopyOnWriteArraySet}???
 * @see CopyOnWriteArraySet#CopyOnWriteArraySet()
 */
public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
    return new CopyOnWriteArraySet<E>();
}

From source file:org.elasticsearch.client.sniff.SnifferTests.java

/**
 * Test behaviour when a bunch of onFailure sniffing rounds are triggered in parallel. Each run will always
 * schedule a subsequent afterFailure round. Also, for each onFailure round that starts, the net scheduled round
 * (either afterFailure or ordinary) gets cancelled.
 *///from w w  w.  j a  v  a  2 s.c o m
public void testSniffOnFailure() throws Exception {
    RestClient restClient = mock(RestClient.class);
    CountingHostsSniffer hostsSniffer = new CountingHostsSniffer();
    final AtomicBoolean initializing = new AtomicBoolean(true);
    final long sniffInterval = randomLongBetween(1, Long.MAX_VALUE);
    final long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE);
    int minNumOnFailureRounds = randomIntBetween(5, 10);
    final CountDownLatch initializingLatch = new CountDownLatch(1);
    final Set<Sniffer.ScheduledTask> ordinaryRoundsTasks = new CopyOnWriteArraySet<>();
    final AtomicReference<Future<?>> initializingFuture = new AtomicReference<>();
    final Set<Sniffer.ScheduledTask> onFailureTasks = new CopyOnWriteArraySet<>();
    final Set<Sniffer.ScheduledTask> afterFailureTasks = new CopyOnWriteArraySet<>();
    final AtomicBoolean onFailureCompleted = new AtomicBoolean(false);
    final CountDownLatch completionLatch = new CountDownLatch(1);
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    try {
        Scheduler scheduler = new Scheduler() {
            @Override
            public Future<?> schedule(final Sniffer.Task task, long delayMillis) {
                if (initializing.compareAndSet(true, false)) {
                    assertEquals(0L, delayMillis);
                    Future<?> future = executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                task.run();
                            } finally {
                                //we need to make sure that the sniffer is initialized, so the sniffOnFailure
                                //call does what it needs to do. Otherwise nothing happens until initialized.
                                initializingLatch.countDown();
                            }
                        }
                    });
                    assertTrue(initializingFuture.compareAndSet(null, future));
                    return future;
                }
                if (delayMillis == 0L) {
                    Future<?> future = executor.submit(task);
                    onFailureTasks.add(new Sniffer.ScheduledTask(task, future));
                    return future;
                }
                if (delayMillis == sniffAfterFailureDelay) {
                    Future<?> future = scheduleOrSubmit(task);
                    afterFailureTasks.add(new Sniffer.ScheduledTask(task, future));
                    return future;
                }

                assertEquals(sniffInterval, delayMillis);
                assertEquals(sniffInterval, task.nextTaskDelay);

                if (onFailureCompleted.get() && onFailureTasks.size() == afterFailureTasks.size()) {
                    completionLatch.countDown();
                    return mock(Future.class);
                }

                Future<?> future = scheduleOrSubmit(task);
                ordinaryRoundsTasks.add(new Sniffer.ScheduledTask(task, future));
                return future;
            }

            private Future<?> scheduleOrSubmit(Sniffer.Task task) {
                if (randomBoolean()) {
                    return executor.schedule(task, randomLongBetween(0L, 200L), TimeUnit.MILLISECONDS);
                } else {
                    return executor.submit(task);
                }
            }

            @Override
            public void shutdown() {
            }
        };
        final Sniffer sniffer = new Sniffer(restClient, hostsSniffer, scheduler, sniffInterval,
                sniffAfterFailureDelay);
        assertTrue("timeout waiting for sniffer to get initialized",
                initializingLatch.await(1000, TimeUnit.MILLISECONDS));

        ExecutorService onFailureExecutor = Executors.newFixedThreadPool(randomIntBetween(5, 20));
        Set<Future<?>> onFailureFutures = new CopyOnWriteArraySet<>();
        try {
            //with tasks executing quickly one after each other, it is very likely that the onFailure round gets skipped
            //as another round is already running. We retry till enough runs get through as that's what we want to test.
            while (onFailureTasks.size() < minNumOnFailureRounds) {
                onFailureFutures.add(onFailureExecutor.submit(new Runnable() {
                    @Override
                    public void run() {
                        sniffer.sniffOnFailure();
                    }
                }));
            }
            assertThat(onFailureFutures.size(), greaterThanOrEqualTo(minNumOnFailureRounds));
            for (Future<?> onFailureFuture : onFailureFutures) {
                assertNull(onFailureFuture.get());
            }
            onFailureCompleted.set(true);
        } finally {
            onFailureExecutor.shutdown();
            onFailureExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
        }

        assertFalse(initializingFuture.get().isCancelled());
        assertTrue(initializingFuture.get().isDone());
        assertNull(initializingFuture.get().get());

        assertTrue("timeout waiting for sniffing rounds to be completed",
                completionLatch.await(1000, TimeUnit.MILLISECONDS));
        assertThat(onFailureTasks.size(), greaterThanOrEqualTo(minNumOnFailureRounds));
        assertEquals(onFailureTasks.size(), afterFailureTasks.size());

        for (Sniffer.ScheduledTask onFailureTask : onFailureTasks) {
            assertFalse(onFailureTask.future.isCancelled());
            assertTrue(onFailureTask.future.isDone());
            assertNull(onFailureTask.future.get());
            assertTrue(onFailureTask.task.hasStarted());
            assertFalse(onFailureTask.task.isSkipped());
        }

        int cancelledTasks = 0;
        int completedTasks = onFailureTasks.size() + 1;
        for (Sniffer.ScheduledTask afterFailureTask : afterFailureTasks) {
            if (assertTaskCancelledOrCompleted(afterFailureTask)) {
                completedTasks++;
            } else {
                cancelledTasks++;
            }
        }

        assertThat(ordinaryRoundsTasks.size(), greaterThan(0));
        for (Sniffer.ScheduledTask task : ordinaryRoundsTasks) {
            if (assertTaskCancelledOrCompleted(task)) {
                completedTasks++;
            } else {
                cancelledTasks++;
            }
        }
        assertEquals(onFailureTasks.size(), cancelledTasks);

        assertEquals(completedTasks, hostsSniffer.runs.get());
        int setHostsRuns = hostsSniffer.runs.get() - hostsSniffer.failures.get() - hostsSniffer.emptyList.get();
        verify(restClient, times(setHostsRuns)).setHosts(Matchers.<HttpHost>anyVararg());
        verifyNoMoreInteractions(restClient);
    } finally {
        executor.shutdown();
        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
    }
}

From source file:org.rifidi.edge.configuration.ConfigurationServiceImpl.java

@Override
public String createService(final String factoryID, final AttributeList attributes, String requiredServiceID)
        throws Exception {
    ServiceFactory<?> factory = factories.get(factoryID);
    if (factory == null) {
        logger.warn("Tried to use a nonexistent factory: " + factoryID);
        throw new CannotCreateServiceException();
    }/*from w  w w  . j av a 2s  .  c  o  m*/

    //Validate and accept only alphanumeric values and underscores
    Pattern pattern = Pattern.compile("^[a-zA-Z0-9_]+$");
    Matcher matcher = pattern.matcher(requiredServiceID);
    if (!matcher.matches()) {
        throw new CannotCreateServiceException(
                "Invalid character for reader id. It's allowed only alphanumeric and underscore characters");
    }

    synchronized (serviceNames) {

        if (serviceNames.contains(requiredServiceID)) {
            throw new CannotCreateServiceException("Service with id: " + requiredServiceID + " already exists");
        }
        serviceNames.add(requiredServiceID);
    }

    DefaultConfigurationImpl config = createAndRegisterConfiguration(requiredServiceID, factoryID, attributes,
            new HashSet<SessionDTO>());

    if (factoryToConfigurations.get(factoryID) == null) {
        factoryToConfigurations.put(factoryID, new CopyOnWriteArraySet<DefaultConfigurationImpl>());
    }
    factoryToConfigurations.get(factoryID).add(config);
    IDToConfigurations.put(requiredServiceID, config);

    if (factory != null) {
        // TODO: Ticket #236
        try {
            factory.createInstance(requiredServiceID);
            return requiredServiceID;
        } catch (IllegalArgumentException e) {
            logger.error("exception", e);
        } catch (InvalidStateException e) {
            logger.error("exception ", e);
        }
    }
    throw new CannotCreateServiceException();
}

From source file:org.springframework.data.keyvalue.redis.listener.RedisMessageListenerContainer.java

private void addListener(MessageListener listener, Collection<? extends Topic> topics) {
    List<byte[]> channels = new ArrayList<byte[]>(topics.size());
    List<byte[]> patterns = new ArrayList<byte[]>(topics.size());

    boolean trace = logger.isTraceEnabled();

    for (Topic topic : topics) {

        ByteArrayWrapper holder = new ByteArrayWrapper(serializer.serialize(topic.getTopic()));

        if (topic instanceof ChannelTopic) {
            Collection<MessageListener> collection = channelMapping.get(holder);
            if (collection == null) {
                collection = new CopyOnWriteArraySet<MessageListener>();
                channelMapping.put(holder, collection);
            }//  w ww  .  j  av  a 2 s  . co m
            collection.add(listener);
            channels.add(holder.getArray());

            if (trace)
                logger.trace("Adding listener '" + listener + "' on channel '" + topic.getTopic() + "'");
        }

        else if (topic instanceof PatternTopic) {
            Collection<MessageListener> collection = patternMapping.get(holder);
            if (collection == null) {
                collection = new CopyOnWriteArraySet<MessageListener>();
                patternMapping.put(holder, collection);
            }
            collection.add(listener);
            patterns.add(holder.getArray());

            if (trace)
                logger.trace("Adding listener '" + listener + "' for pattern '" + topic.getTopic() + "'");
        }

        else {
            throw new IllegalArgumentException("Unknown topic type '" + topic.getClass() + "'");
        }
    }

    // check the current listening state
    if (listening) {
        subscriptionTask.subscribeChannel(channels.toArray(new byte[channels.size()][]));
        subscriptionTask.subscribePattern(patterns.toArray(new byte[patterns.size()][]));
    }
}

From source file:org.sakaiproject.site.impl.BaseSiteService.java

/**
 * Final initialization, once all dependencies are set.
 *///w  w  w  .jav  a  2s.  c o m
public void init() {
    siteAdvisors = new ArrayList<SiteAdvisor>();
    // Concurrent so that we never get ConcurrentModificationException when iterating.
    siteRemovalAdvisors = new CopyOnWriteArraySet<SiteRemovalAdvisor>();

    try {
        // Get resource bundle
        String resourceClass = serverConfigurationService().getString(RESOURCECLASS, DEFAULT_RESOURCECLASS);
        String resourceBundle = serverConfigurationService().getString(RESOURCEBUNDLE, DEFAULT_RESOURCEBUNDLE);
        rb = new Resource().getLoader(resourceClass, resourceBundle);

        m_relativeAccessPoint = REFERENCE_ROOT;

        // construct storage and read
        m_storage = newStorage();
        storage().open();

        if (m_regenerateIds) {
            regenerateAllSiteIds();
            m_regenerateIds = false;
        }

        // <= 0 minutes indicates no caching desired
        if (m_cacheSeconds > 0) {
            m_siteCache = new SiteCacheSafe(memoryService(), eventTrackingService());
        }

        // Register our user-site cache property
        serverConfigurationService().registerConfigItem(BasicConfigItem
                .makeDefaultedConfigItem(PROP_CACHE_USER_SITES, true, "org.sakaiproject.api.SiteService"));

        // Get the user-site cache from the MemoryService for now -- maybe directly from cache manager or Spring later.
        // Also register as an observer so we can catch site updates and invalidate.
        if (serverConfigurationService().getBoolean(PROP_CACHE_USER_SITES, true)) {
            m_userSiteCache = memoryService().newCache(USER_SITE_CACHE);
            eventTrackingService().addObserver(this);
        }

        // register as an entity producer
        entityManager().registerEntityProducer(this, REFERENCE_ROOT);

        // register functions
        functionManager().registerFunction(SITE_ROLE_SWAP);
        functionManager().registerFunction(SITE_VISIT);
        functionManager().registerFunction(SITE_VISIT_UNPUBLISHED);
        functionManager().registerFunction(SECURE_ADD_SITE);
        functionManager().registerFunction(SECURE_ADD_USER_SITE);
        functionManager().registerFunction(SECURE_ADD_PORTFOLIO_SITE);
        functionManager().registerFunction(SECURE_REMOVE_SITE);
        functionManager().registerFunction(SECURE_UPDATE_SITE);
        functionManager().registerFunction(SECURE_VIEW_ROSTER);
        functionManager().registerFunction(SECURE_UPDATE_SITE_MEMBERSHIP);
        functionManager().registerFunction(SECURE_UPDATE_GROUP_MEMBERSHIP);
        functionManager().registerFunction(SECURE_ADD_COURSE_SITE);
        functionManager().registerFunction(SITE_VISIT_SOFTLY_DELETED);
        functionManager().registerFunction(SECURE_REMOVE_SOFTLY_DELETED_SITE);
        functionManager().registerFunction(SECURE_ADD_PROJECT_SITE);
        functionManager().registerFunction(SECURE_IMPORT_ARCHIVE);

        // sfoster9@uwo.ca
        // assign a new JoinSiteDelegate to handle the join methods; provide it services from this class
        joinSiteDelegate = new JoinSiteDelegate(this, securityService(), userDirectoryService());

        // SAK-29138
        m_siteTitleAdvisor = (SiteTitleAdvisor) ComponentManager.get(SiteTitleAdvisor.class);
    } catch (Exception t) {
        M_log.error(".init(): ", t);
    }
}

From source file:org.opendaylight.netvirt.dhcpservice.DhcpExternalTunnelManager.java

public void updateLocalCache(BigInteger designatedDpnId, IpAddress tunnelIp, String elanInstanceName) {
    Pair<IpAddress, String> tunnelIpElanName = new ImmutablePair<>(tunnelIp, elanInstanceName);
    Set<Pair<IpAddress, String>> tunnelIpElanNameSet;
    tunnelIpElanNameSet = designatedDpnsToTunnelIpElanNameCache.get(designatedDpnId);
    if (tunnelIpElanNameSet == null) {
        tunnelIpElanNameSet = new CopyOnWriteArraySet<>();
    }//from w ww  .j  av  a 2  s . c o m
    tunnelIpElanNameSet.add(tunnelIpElanName);
    LOG.trace("Updating designatedDpnsToTunnelIpElanNameCache for designatedDpn {} value {}", designatedDpnId,
            tunnelIpElanNameSet);
    designatedDpnsToTunnelIpElanNameCache.put(designatedDpnId, tunnelIpElanNameSet);
}

From source file:org.opendaylight.netvirt.dhcpservice.DhcpExternalTunnelManager.java

public void updateLocalCache(IpAddress tunnelIp, String elanInstanceName, String vmMacAddress) {
    Pair<IpAddress, String> tunnelIpElanName = new ImmutablePair<>(tunnelIp, elanInstanceName);
    Set<String> setOfExistingVmMacAddress;
    setOfExistingVmMacAddress = tunnelIpElanNameToVmMacCache.get(tunnelIpElanName);
    if (setOfExistingVmMacAddress == null) {
        setOfExistingVmMacAddress = new CopyOnWriteArraySet<>();
    }//w  ww.ja  v  a2  s  .c  om
    setOfExistingVmMacAddress.add(vmMacAddress);
    LOG.trace("Updating tunnelIpElanNameToVmMacCache for tunnelIpElanName {} value {}", tunnelIpElanName,
            setOfExistingVmMacAddress);
    tunnelIpElanNameToVmMacCache.put(tunnelIpElanName, setOfExistingVmMacAddress);
    updateExistingVMTunnelIPCache(tunnelIp, elanInstanceName, vmMacAddress);
}