Java 类java.util.concurrent.CopyOnWriteArraySet 实例源码

项目:GitHub    文件:ConnectionSpecTest.java   
@Test public void equalsAndHashCode() throws Exception {
  ConnectionSpec allCipherSuites = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .allEnabledCipherSuites()
      .build();
  ConnectionSpec allTlsVersions = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .allEnabledTlsVersions()
      .build();

  Set<Object> set = new CopyOnWriteArraySet<>();
  assertTrue(set.add(ConnectionSpec.MODERN_TLS));
  assertTrue(set.add(ConnectionSpec.COMPATIBLE_TLS));
  assertTrue(set.add(ConnectionSpec.CLEARTEXT));
  assertTrue(set.add(allTlsVersions));
  assertTrue(set.add(allCipherSuites));

  assertTrue(set.remove(ConnectionSpec.MODERN_TLS));
  assertTrue(set.remove(ConnectionSpec.COMPATIBLE_TLS));
  assertTrue(set.remove(ConnectionSpec.CLEARTEXT));
  assertTrue(set.remove(allTlsVersions));
  assertTrue(set.remove(allCipherSuites));
  assertTrue(set.isEmpty());
}
项目:GitHub    文件:ConnectionSpecTest.java   
@Test public void equalsAndHashCode() throws Exception {
  ConnectionSpec allCipherSuites = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .allEnabledCipherSuites()
      .build();
  ConnectionSpec allTlsVersions = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .allEnabledTlsVersions()
      .build();

  Set<Object> set = new CopyOnWriteArraySet<>();
  assertTrue(set.add(ConnectionSpec.MODERN_TLS));
  assertTrue(set.add(ConnectionSpec.COMPATIBLE_TLS));
  assertTrue(set.add(ConnectionSpec.CLEARTEXT));
  assertTrue(set.add(allTlsVersions));
  assertTrue(set.add(allCipherSuites));

  assertTrue(set.remove(ConnectionSpec.MODERN_TLS));
  assertTrue(set.remove(ConnectionSpec.COMPATIBLE_TLS));
  assertTrue(set.remove(ConnectionSpec.CLEARTEXT));
  assertTrue(set.remove(allTlsVersions));
  assertTrue(set.remove(allCipherSuites));
  assertTrue(set.isEmpty());
}
项目:incubator-netbeans    文件:SessionBridge.java   
private void addSessionChangerListener(SessionChanger sc) {
    Set<String> actions = sc.getActions();
    synchronized (sessionChangers) {
        for (String action : actions) {
            Set<SessionChanger> scs = sessionChangers.get(action);
            if (scs == null) {
                sessionChangers.put(action, Collections.singleton(sc));
            } else {
                if (scs.size() == 1) {
                    SessionChanger old = scs.iterator().next();
                    scs = new CopyOnWriteArraySet<SessionChanger>();
                    scs.add(old);
                }
                scs.add(sc);
            }
        }
    }
}
项目:RestyPass    文件:DefaultCircuitBreaker.java   
@Override
public void start() {
    if (!started) {
        startLock.lock();
        try {
            if (!started) {
                this.eventKey = KEY_PREFIX + UUID.randomUUID().toString().replace("-", "").toLowerCase();
                this.segmentMap = new ConcurrentHashMap<>();
                this.statusMap = new ConcurrentHashMap<>();
                this.brokenServerSet = new CopyOnWriteArraySet<>();
                this.commandQueue = new LinkedBlockingQueue<>();
                this.halfOpenLockMap = new ConcurrentHashMap<>(64);
                this.registerEvent();
                this.startTask();
                started = true;
            }
        } finally {
            startLock.unlock();
        }
    }
}
项目:airgram    文件:ExoPlayerImpl.java   
/**
 * Constructs an instance. Must be invoked from a thread that has an associated {@link Looper}.
 *
 * @param rendererCount The number of {@link TrackRenderer}s that will be passed to
 *     {@link #prepare(TrackRenderer[])}.
 * @param minBufferMs A minimum duration of data that must be buffered for playback to start
 *     or resume following a user action such as a seek.
 * @param minRebufferMs A minimum duration of data that must be buffered for playback to resume
 *     after a player invoked rebuffer (i.e. a rebuffer that occurs due to buffer depletion, and
 *     not due to a user action such as starting playback or seeking).
 */
@SuppressLint("HandlerLeak")
public ExoPlayerImpl(int rendererCount, int minBufferMs, int minRebufferMs) {
  Log.i(TAG, "Init " + ExoPlayerLibraryInfo.VERSION);
  this.playWhenReady = false;
  this.playbackState = STATE_IDLE;
  this.listeners = new CopyOnWriteArraySet<>();
  this.trackFormats = new MediaFormat[rendererCount][];
  this.selectedTrackIndices = new int[rendererCount];
  eventHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      ExoPlayerImpl.this.handleEvent(msg);
    }
  };
  internalPlayer = new ExoPlayerImplInternal(eventHandler, playWhenReady, selectedTrackIndices,
      minBufferMs, minRebufferMs);
}
项目:guava-mock    文件:SubscriberRegistry.java   
/**
 * Registers all subscriber methods on the given listener object.
 */
void register(Object listener) {
  Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener);

  for (Map.Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) {
    Class<?> eventType = entry.getKey();
    Collection<Subscriber> eventMethodsInListener = entry.getValue();

    CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType);

    if (eventSubscribers == null) {
      CopyOnWriteArraySet<Subscriber> newSet = new CopyOnWriteArraySet<Subscriber>();
      eventSubscribers =
          MoreObjects.firstNonNull(subscribers.putIfAbsent(eventType, newSet), newSet);
    }

    eventSubscribers.addAll(eventMethodsInListener);
  }
}
项目:guava-mock    文件:SubscriberRegistry.java   
/**
 * Unregisters all subscribers on the given listener object.
 */
void unregister(Object listener) {
  Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener);

  for (Map.Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) {
    Class<?> eventType = entry.getKey();
    Collection<Subscriber> listenerMethodsForType = entry.getValue();

    CopyOnWriteArraySet<Subscriber> currentSubscribers = subscribers.get(eventType);
    if (currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType)) {
      // if removeAll returns true, all we really know is that at least one subscriber was
      // removed... however, barring something very strange we can assume that if at least one
      // subscriber was removed, all subscribers on listener for that event type were... after
      // all, the definition of subscribers on a particular class is totally static
      throw new IllegalArgumentException(
          "missing event subscriber for an annotated method. Is " + listener + " registered?");
    }

    // don't try to remove the set if it's empty; that can't be done safely without a lock
    // anyway, if the set is empty it'll just be wrapping an array of length 0
  }
}
项目:guava-mock    文件:SubscriberRegistry.java   
/**
 * Gets an iterator representing an immutable snapshot of all subscribers to the given event at
 * the time this method is called.
 */
Iterator<Subscriber> getSubscribers(Object event) {
  ImmutableSet<Class<?>> eventTypes = flattenHierarchy(event.getClass());

  List<Iterator<Subscriber>> subscriberIterators =
      Lists.newArrayListWithCapacity(eventTypes.size());

  for (Class<?> eventType : eventTypes) {
    CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType);
    if (eventSubscribers != null) {
      // eager no-copy snapshot
      subscriberIterators.add(eventSubscribers.iterator());
    }
  }

  return Iterators.concat(subscriberIterators.iterator());
}
项目:guava-mock    文件:TestsForSetsInJavaUtil.java   
public Test testsForCopyOnWriteArraySet() {
  return SetTestSuiteBuilder.using(
          new TestStringSetGenerator() {
            @Override
            public Set<String> create(String[] elements) {
              return new CopyOnWriteArraySet<String>(MinimalCollection.of(elements));
            }
          })
      .named("CopyOnWriteArraySet")
      .withFeatures(
          CollectionFeature.SUPPORTS_ADD,
          CollectionFeature.SUPPORTS_REMOVE,
          CollectionFeature.SERIALIZABLE,
          CollectionFeature.ALLOWS_NULL_VALUES,
          CollectionFeature.KNOWN_ORDER,
          CollectionSize.ANY)
      .suppressing(suppressForCopyOnWriteArraySet())
      .createTestSuite();
}
项目:LightSIP    文件:SIPClientTransactionImpl.java   
/**
 * Creates a new client transaction.
 * 
 * @param newSIPStack Transaction stack this transaction belongs to.
 * @param newChannelToUse Channel to encapsulate.
 * @return the created client transaction.
 */
protected SIPClientTransactionImpl(SIPTransactionStack newSIPStack, MessageChannel newChannelToUse)
{
  super(newSIPStack, newChannelToUse);
  // Create a random branch parameter for this transaction
  setBranch(Utils.getInstance().generateBranchId());
  this.setEncapsulatedChannel(newChannelToUse);
  this.notifyOnRetransmit = false;
  this.timeoutIfStillInCallingState = false;

  if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
    logger.logDebug("Creating clientTransaction " + this);
    logger.logStackTrace();
  }
  // this.startTransactionTimer();
  this.sipDialogs = new CopyOnWriteArraySet<String>();
}
项目:lams    文件:HostTable.java   
public synchronized HostTable addRoute(H host, String virtualHost, String contextPath) {
    Set<Target> hostData = hosts.get(host);
    if(hostData == null) {
        throw UndertowMessages.MESSAGES.hostHasNotBeenRegistered(host);
    }
    hostData.add(new Target(virtualHost, contextPath));
    PathMatcher<Set<H>> paths = targets.get(virtualHost);
    if(paths == null) {
        paths = new PathMatcher<>();
        targets.put(virtualHost, paths);
    }
    Set<H> hostSet = paths.getPrefixPath(contextPath);
    if(hostSet == null) {
        hostSet = new CopyOnWriteArraySet<>();
        paths.addPrefixPath(contextPath, hostSet);
    }
    hostSet.add(host);
    return this;
}
项目:PlusGram    文件:ExoPlayerImpl.java   
/**
 * Constructs an instance. Must be invoked from a thread that has an associated {@link Looper}.
 *
 * @param rendererCount The number of {@link TrackRenderer}s that will be passed to
 *     {@link #prepare(TrackRenderer[])}.
 * @param minBufferMs A minimum duration of data that must be buffered for playback to start
 *     or resume following a user action such as a seek.
 * @param minRebufferMs A minimum duration of data that must be buffered for playback to resume
 *     after a player invoked rebuffer (i.e. a rebuffer that occurs due to buffer depletion, and
 *     not due to a user action such as starting playback or seeking).
 */
@SuppressLint("HandlerLeak")
public ExoPlayerImpl(int rendererCount, int minBufferMs, int minRebufferMs) {
  Log.i(TAG, "Init " + ExoPlayerLibraryInfo.VERSION);
  this.playWhenReady = false;
  this.playbackState = STATE_IDLE;
  this.listeners = new CopyOnWriteArraySet<>();
  this.trackFormats = new MediaFormat[rendererCount][];
  this.selectedTrackIndices = new int[rendererCount];
  eventHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      ExoPlayerImpl.this.handleEvent(msg);
    }
  };
  internalPlayer = new ExoPlayerImplInternal(eventHandler, playWhenReady, selectedTrackIndices,
      minBufferMs, minRebufferMs);
}
项目:OpenYOLO-Android    文件:BroadcastQueryClient.java   
PendingQuery(
        String dataType,
        byte[] queryMessage,
        long timeoutInMs,
        QueryCallback queryCallback) {
    mDataType = dataType;
    mQueryMessage = queryMessage;
    mTimeoutInMs = timeoutInMs;

    mRespondersById = buildRespondersById();
    mPendingResponses = new CopyOnWriteArraySet<>();
    for (long responderId : mRespondersById.keySet()) {
        mPendingResponses.add(responderId);
    }
    mResponses = new ConcurrentHashMap<>();
    mQueryCallback = queryCallback;
}
项目:monarch    文件:MBeanProxyInfoRepository.java   
/**
 * Add the {@link ProxyInfo} into repository for future quick access
 * 
 * @param member Distributed Member
 * @param proxyInfo Proxy Info instance
 */
protected void addProxyToRepository(DistributedMember member, ProxyInfo proxyInfo) {
  ObjectName objectName = proxyInfo.getObjectName();
  if (logger.isTraceEnabled()) {
    logger.trace("ADDED TO PROXY REPO : {}", proxyInfo.getObjectName());
  }

  objectNameIndex.put(objectName, proxyInfo);
  if (memberIndex.get(member) != null) {
    memberIndex.get(member).add(proxyInfo.getObjectName());
  } else {
    Set<ObjectName> proxyInfoSet = new CopyOnWriteArraySet<ObjectName>();
    proxyInfoSet.add(proxyInfo.getObjectName());
    memberIndex.put(member, proxyInfoSet);
  }

}
项目:monarch    文件:ClientMetadataService.java   
private void addClientPartitionAdvisor(String regionFullPath, ClientPartitionAdvisor advisor) {
  if (this.cache.isClosed() || this.clientPRAdvisors == null) {
    return;
  }
  try {
    this.clientPRAdvisors.put(regionFullPath, advisor);
    if (advisor.getColocatedWith() != null) {
      String parentRegionPath = advisor.getColocatedWith();
      Set<ClientPartitionAdvisor> colocatedAdvisors =
          this.colocatedPRAdvisors.get(parentRegionPath);
      if (colocatedAdvisors == null) {
        colocatedAdvisors = new CopyOnWriteArraySet<ClientPartitionAdvisor>();
        this.colocatedPRAdvisors.put(parentRegionPath, colocatedAdvisors);
      }
      colocatedAdvisors.add(advisor);
    }
  } catch (Exception npe) {
    // ignore, shutdown case
  }

}
项目:monarch    文件:AttributesFactory.java   
public void addGatewaySenderId(String gatewaySenderId) {
  if (this.gatewaySenderIds == null) {
    this.gatewaySenderIds = new CopyOnWriteArraySet<String>();
    this.gatewaySenderIds.add(gatewaySenderId);
  } else {
    synchronized (this.gatewaySenderIds) { // TODO: revisit this
      // synchronization : added as per
      // above code
      if (this.gatewaySenderIds.contains(gatewaySenderId)) {
        throw new IllegalArgumentException(
            LocalizedStrings.AttributesFactory_GATEWAY_SENDER_ID_0_IS_ALREADY_ADDED
                .toLocalizedString(gatewaySenderId));
      }
      this.gatewaySenderIds.add(gatewaySenderId);
    }
  }
  setHasGatewaySenderIds(true);
}
项目:monarch    文件:AttributesFactory.java   
public void addAsyncEventQueueId(String asyncEventQueueId) {
  if (this.asyncEventQueueIds == null) {
    this.asyncEventQueueIds = new CopyOnWriteArraySet<String>();
    this.asyncEventQueueIds.add(asyncEventQueueId);
  } else {
    synchronized (this.asyncEventQueueIds) { // TODO: revisit this
      // synchronization : added as per
      // above code
      if (this.asyncEventQueueIds.contains(asyncEventQueueId)) {
        throw new IllegalArgumentException(
            LocalizedStrings.AttributesFactory_ASYNC_EVENT_QUEUE_ID_0_IS_ALREADY_ADDED
                .toLocalizedString(asyncEventQueueId));
      }
      this.asyncEventQueueIds.add(asyncEventQueueId);
    }
  }
  setHasAsyncEventListeners(true);
}
项目:ibm-cos-sdk-java    文件:DelegatingDnsResolverTest.java   
@Before
public void resetClientConfiguration() {
    dnsResolutionCounter = new AtomicInteger(0);
    requestedHosts = new CopyOnWriteArraySet<String>();

    ClientConfiguration clientConfiguration = new ClientConfiguration();
    clientConfiguration.withMaxErrorRetry(0);
    clientConfiguration.withDnsResolver(new DnsResolver() {
        DnsResolver system = new SystemDefaultDnsResolver();
        @Override
        public InetAddress[] resolve(String host) throws UnknownHostException {
            dnsResolutionCounter.incrementAndGet();
            requestedHosts.add(host);
            return system.resolve(host);
        }
    });

    testedClient = new AmazonHttpClient(clientConfiguration);
}
项目:openjdk-jdk10    文件:CopyOnWriteArraySetTest.java   
/**
 * containsAll returns true for collections with subset of elements
 */
public void testContainsAll() {
    Collection full = populatedSet(3);
    assertTrue(full.containsAll(full));
    assertTrue(full.containsAll(Arrays.asList()));
    assertTrue(full.containsAll(Arrays.asList(one)));
    assertTrue(full.containsAll(Arrays.asList(one, two)));
    assertFalse(full.containsAll(Arrays.asList(one, two, six)));
    assertFalse(full.containsAll(Arrays.asList(six)));

    CopyOnWriteArraySet empty1 = new CopyOnWriteArraySet(Arrays.asList());
    CopyOnWriteArraySet empty2 = new CopyOnWriteArraySet(Arrays.asList());
    assertTrue(empty1.containsAll(empty2));
    assertTrue(empty1.containsAll(empty1));
    assertFalse(empty1.containsAll(full));
    assertTrue(full.containsAll(empty1));

    try {
        full.containsAll(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
项目:openjdk-jdk10    文件:CopyOnWriteArraySetTest.java   
/**
 * iterator() returns an iterator containing the elements of the
 * set in insertion order
 */
public void testIterator() {
    Collection empty = new CopyOnWriteArraySet();
    assertFalse(empty.iterator().hasNext());
    try {
        empty.iterator().next();
        shouldThrow();
    } catch (NoSuchElementException success) {}

    Integer[] elements = new Integer[SIZE];
    for (int i = 0; i < SIZE; i++)
        elements[i] = i;
    shuffle(elements);
    Collection<Integer> full = populatedSet(elements);

    Iterator it = full.iterator();
    for (int j = 0; j < SIZE; j++) {
        assertTrue(it.hasNext());
        assertEquals(elements[j], it.next());
    }
    assertIteratorExhausted(it);
}
项目:googles-monorepo-demo    文件:SubscriberRegistry.java   
/**
 * Registers all subscriber methods on the given listener object.
 */
void register(Object listener) {
  Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener);

  for (Map.Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) {
    Class<?> eventType = entry.getKey();
    Collection<Subscriber> eventMethodsInListener = entry.getValue();

    CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType);

    if (eventSubscribers == null) {
      CopyOnWriteArraySet<Subscriber> newSet = new CopyOnWriteArraySet<Subscriber>();
      eventSubscribers =
          MoreObjects.firstNonNull(subscribers.putIfAbsent(eventType, newSet), newSet);
    }

    eventSubscribers.addAll(eventMethodsInListener);
  }
}
项目:googles-monorepo-demo    文件:SubscriberRegistry.java   
/**
 * Unregisters all subscribers on the given listener object.
 */
void unregister(Object listener) {
  Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener);

  for (Map.Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) {
    Class<?> eventType = entry.getKey();
    Collection<Subscriber> listenerMethodsForType = entry.getValue();

    CopyOnWriteArraySet<Subscriber> currentSubscribers = subscribers.get(eventType);
    if (currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType)) {
      // if removeAll returns true, all we really know is that at least one subscriber was
      // removed... however, barring something very strange we can assume that if at least one
      // subscriber was removed, all subscribers on listener for that event type were... after
      // all, the definition of subscribers on a particular class is totally static
      throw new IllegalArgumentException(
          "missing event subscriber for an annotated method. Is " + listener + " registered?");
    }

    // don't try to remove the set if it's empty; that can't be done safely without a lock
    // anyway, if the set is empty it'll just be wrapping an array of length 0
  }
}
项目:googles-monorepo-demo    文件:SubscriberRegistry.java   
/**
 * Gets an iterator representing an immutable snapshot of all subscribers to the given event at
 * the time this method is called.
 */
Iterator<Subscriber> getSubscribers(Object event) {
  ImmutableSet<Class<?>> eventTypes = flattenHierarchy(event.getClass());

  List<Iterator<Subscriber>> subscriberIterators =
      Lists.newArrayListWithCapacity(eventTypes.size());

  for (Class<?> eventType : eventTypes) {
    CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType);
    if (eventSubscribers != null) {
      // eager no-copy snapshot
      subscriberIterators.add(eventSubscribers.iterator());
    }
  }

  return Iterators.concat(subscriberIterators.iterator());
}
项目:googles-monorepo-demo    文件:TestsForSetsInJavaUtil.java   
public Test testsForCopyOnWriteArraySet() {
  return SetTestSuiteBuilder.using(
          new TestStringSetGenerator() {
            @Override
            public Set<String> create(String[] elements) {
              return new CopyOnWriteArraySet<String>(MinimalCollection.of(elements));
            }
          })
      .named("CopyOnWriteArraySet")
      .withFeatures(
          CollectionFeature.SUPPORTS_ADD,
          CollectionFeature.SUPPORTS_REMOVE,
          CollectionFeature.SERIALIZABLE,
          CollectionFeature.ALLOWS_NULL_VALUES,
          CollectionFeature.KNOWN_ORDER,
          CollectionSize.ANY)
      .suppressing(suppressForCopyOnWriteArraySet())
      .createTestSuite();
}
项目:Mega-Walls    文件:BasicGame.java   
public BasicGame(Map map)
{
    this.map = map;
    this.spectators = new HashSet<User>();
    this.teams = new HashSet<>();
    this.usersInLobby = new CopyOnWriteArraySet<>();

    for (TeamColor color : map.getAvailableTeams())
    {
        teams.add(new BasicTeam(this, color));
    }

    this.gameStartingRunnable = new GameStartingRunnable(this);

    this.startedOn = null;
    this.endedOn = null;
    this.winner = null;

    this.state = GameState.LOBBY;
}
项目:codebuff    文件:SubscriberRegistry.java   
/**
 * Unregisters all subscribers on the given listener object.
 */
void unregister(Object listener) {
  Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener);

  for (Map.Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) {
    Class<?> eventType = entry.getKey();
    Collection<Subscriber> listenerMethodsForType = entry.getValue();

    CopyOnWriteArraySet<Subscriber> currentSubscribers = subscribers.get(eventType);
    if (currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType)) {
      // if removeAll returns true, all we really know is that at least one subscriber was
      // removed... however, barring something very strange we can assume that if at least one
      // subscriber was removed, all subscribers on listener for that event type were... after
      // all, the definition of subscribers on a particular class is totally static
      throw new IllegalArgumentException(
          "missing event subscriber for an annotated method. Is " + listener + " registered?");
    }

    // don't try to remove the set if it's empty; that can't be done safely without a lock
    // anyway, if the set is empty it'll just be wrapping an array of length 0
  }
}
项目:openjdk9    文件:CopyOnWriteArraySetTest.java   
/**
 * containsAll returns true for collections with subset of elements
 */
public void testContainsAll() {
    Collection full = populatedSet(3);
    assertTrue(full.containsAll(full));
    assertTrue(full.containsAll(Arrays.asList()));
    assertTrue(full.containsAll(Arrays.asList(one)));
    assertTrue(full.containsAll(Arrays.asList(one, two)));
    assertFalse(full.containsAll(Arrays.asList(one, two, six)));
    assertFalse(full.containsAll(Arrays.asList(six)));

    CopyOnWriteArraySet empty1 = new CopyOnWriteArraySet(Arrays.asList());
    CopyOnWriteArraySet empty2 = new CopyOnWriteArraySet(Arrays.asList());
    assertTrue(empty1.containsAll(empty2));
    assertTrue(empty1.containsAll(empty1));
    assertFalse(empty1.containsAll(full));
    assertTrue(full.containsAll(empty1));

    try {
        full.containsAll(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
项目:openjdk9    文件:CopyOnWriteArraySetTest.java   
/**
 * iterator() returns an iterator containing the elements of the
 * set in insertion order
 */
public void testIterator() {
    Collection empty = new CopyOnWriteArraySet();
    assertFalse(empty.iterator().hasNext());
    try {
        empty.iterator().next();
        shouldThrow();
    } catch (NoSuchElementException success) {}

    Integer[] elements = new Integer[SIZE];
    for (int i = 0; i < SIZE; i++)
        elements[i] = i;
    Collections.shuffle(Arrays.asList(elements));
    Collection<Integer> full = populatedSet(elements);

    Iterator it = full.iterator();
    for (int j = 0; j < SIZE; j++) {
        assertTrue(it.hasNext());
        assertEquals(elements[j], it.next());
    }
    assertIteratorExhausted(it);
}
项目:PriorityOkHttp    文件:ConnectionSpecTest.java   
@Test public void equalsAndHashCode() throws Exception {
  ConnectionSpec allCipherSuites = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .allEnabledCipherSuites()
      .build();
  ConnectionSpec allTlsVersions = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .allEnabledTlsVersions()
      .build();

  Set<Object> set = new CopyOnWriteArraySet<>();
  assertTrue(set.add(ConnectionSpec.MODERN_TLS));
  assertTrue(set.add(ConnectionSpec.COMPATIBLE_TLS));
  assertTrue(set.add(ConnectionSpec.CLEARTEXT));
  assertTrue(set.add(allTlsVersions));
  assertTrue(set.add(allCipherSuites));

  assertTrue(set.remove(ConnectionSpec.MODERN_TLS));
  assertTrue(set.remove(ConnectionSpec.COMPATIBLE_TLS));
  assertTrue(set.remove(ConnectionSpec.CLEARTEXT));
  assertTrue(set.remove(allTlsVersions));
  assertTrue(set.remove(allCipherSuites));
  assertTrue(set.isEmpty());
}
项目:Okhttp    文件:ConnectionSpecTest.java   
@Test public void equalsAndHashCode() throws Exception {
  ConnectionSpec allCipherSuites = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .allEnabledCipherSuites()
      .build();
  ConnectionSpec allTlsVersions = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .allEnabledTlsVersions()
      .build();

  Set<Object> set = new CopyOnWriteArraySet<>();
  assertTrue(set.add(ConnectionSpec.MODERN_TLS));
  assertTrue(set.add(ConnectionSpec.COMPATIBLE_TLS));
  assertTrue(set.add(ConnectionSpec.CLEARTEXT));
  assertTrue(set.add(allTlsVersions));
  assertTrue(set.add(allCipherSuites));

  assertTrue(set.remove(ConnectionSpec.MODERN_TLS));
  assertTrue(set.remove(ConnectionSpec.COMPATIBLE_TLS));
  assertTrue(set.remove(ConnectionSpec.CLEARTEXT));
  assertTrue(set.remove(allTlsVersions));
  assertTrue(set.remove(allCipherSuites));
  assertTrue(set.isEmpty());
}
项目:av-service    文件:AvCheckMessageProcessor.java   
/**
 * Creates a processor with a given thread count, service ID, anti-virus service and
 * message info service.
 *
 * @param threadCount        the processing thread count
 * @param serviceId          the service ID string
 * @param avService          the anti-virus service
 * @param messageInfoService the message info service
 */
@Autowired
public AvCheckMessageProcessor(
        int threadCount,
        String serviceId,
        AvService avService,
        MessageInfoService messageInfoService
) {
    this.threadCount = threadCount;
    this.serviceId = serviceId;
    this.avService = requireNonNull(avService);
    this.messageInfoService = requireNonNull(messageInfoService);

    ThreadFactory threadFactory = new CustomThreadFactory("check-message-processor-");
    executorService = Executors.newFixedThreadPool(threadCount, threadFactory);

    statusStorage = new BasicMessageStatusStorage(CACHE_TIMEOUT);

    avMessageListeners = new CopyOnWriteArraySet<>();
}
项目:gemfirexd-oss    文件:MBeanProxyInfoRepository.java   
/**
 * Add the {@link ProxyInfo} into repository for future quick access
 * 
 * @param member
 *          Distributed Member
 * @param proxyInfo
 *          Proxy Info instance
 */
protected void addProxyToRepository(DistributedMember member,
    ProxyInfo proxyInfo) {
  ObjectName objectName = proxyInfo.getObjectName();
  if (logger.finestEnabled()) {
    logger.finest("ADDED TO PROXY REPO : "
        + proxyInfo.getObjectName().toString());
  }

  objectNameIndex.put(objectName, proxyInfo);
  if (memberIndex.get(member) != null) {
    memberIndex.get(member).add(proxyInfo.getObjectName());
  } else {
    Set<ObjectName> proxyInfoSet = new CopyOnWriteArraySet<ObjectName>();
    proxyInfoSet.add(proxyInfo.getObjectName());
    memberIndex.put(member, proxyInfoSet);
  }

}
项目:gemfirexd-oss    文件:ClientMetadataService.java   
private void addClientPartitionAdvisor(String regionFullPath,
    ClientPartitionAdvisor advisor) {
  if (this.cache.isClosed() || this.clientPRAdvisors == null) {
    return;
  }
  try {
    this.clientPRAdvisors.put(regionFullPath, advisor);
    if (advisor.getColocatedWith() != null) {
      String parentRegionPath = advisor.getColocatedWith();
      Set<ClientPartitionAdvisor> colocatedAdvisors = this.colocatedPRAdvisors.get(parentRegionPath);
      if(colocatedAdvisors == null){
        colocatedAdvisors = new CopyOnWriteArraySet<ClientPartitionAdvisor>();
        this.colocatedPRAdvisors.put(parentRegionPath, colocatedAdvisors);
      }
      colocatedAdvisors.add(advisor);
    }
  }
  catch (Exception npe) {
    // ignore, shutdown case
  }

}
项目:gemfirexd-oss    文件:AttributesFactory.java   
public void addGatewaySenderId(String gatewaySenderId) {
  if(this.gatewaySenderIds == null){
    this.gatewaySenderIds = new CopyOnWriteArraySet<String>();
    this.gatewaySenderIds.add(gatewaySenderId);
  }else{
    synchronized (this.gatewaySenderIds) { // TODO: revisit this
      // synchronization : added as per
      // above code
      if (this.gatewaySenderIds.contains(gatewaySenderId)) {
        throw new IllegalArgumentException(
            LocalizedStrings.AttributesFactory_GATEWAY_SENDER_ID_0_IS_ALREADY_ADDED
            .toLocalizedString(gatewaySenderId));
      }
      this.gatewaySenderIds.add(gatewaySenderId);
    }
  }
  setHasGatewaySenderIds(true);
}
项目:gemfirexd-oss    文件:AttributesFactory.java   
public void addAsyncEventQueueId(String asyncEventQueueId) {
  if(this.asyncEventQueueIds == null){
    this.asyncEventQueueIds = new CopyOnWriteArraySet<String>();
    this.asyncEventQueueIds.add(asyncEventQueueId);
  } else{
    synchronized (this.asyncEventQueueIds) { // TODO: revisit this
      // synchronization : added as per
      // above code
      if (this.asyncEventQueueIds.contains(asyncEventQueueId)) {
        throw new IllegalArgumentException(
            LocalizedStrings.AttributesFactory_ASYNC_EVENT_QUEUE_ID_0_IS_ALREADY_ADDED
            .toLocalizedString(asyncEventQueueId));
      }
      this.asyncEventQueueIds.add(asyncEventQueueId);
    }
  }
  setHasAsyncEventListeners(true);
}
项目:gemfirexd-oss    文件:AttributesFactory.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object clone() {
  try {
    RegionAttributesImpl<K,V> copy = (RegionAttributesImpl<K,V>) super.clone();
    if (copy.getIndexes() != null) {
      copy.setIndexes(new ArrayList(copy.getIndexes()));
    }
    if (copy.partitionAttributes != null) {
      copy.partitionAttributes = ((PartitionAttributesImpl)copy.partitionAttributes).copy();
    }
    if (copy.cacheListeners != null) {
      copy.cacheListeners = new ArrayList<CacheListener<K,V>>(copy.cacheListeners);
    }
    if (copy.gatewaySenderIds != null) {
      copy.gatewaySenderIds =  new CopyOnWriteArraySet<String>(copy.gatewaySenderIds);
    }
    if (copy.asyncEventQueueIds != null) {
      copy.asyncEventQueueIds = new CopyOnWriteArraySet<String>(copy.asyncEventQueueIds);
    }
    return copy;
  }
  catch (CloneNotSupportedException e) {
    throw new InternalError(LocalizedStrings.AttributesFactory_CLONENOTSUPPORTEDEXCEPTION_THROWN_IN_CLASS_THAT_IMPLEMENTS_CLONEABLE.toLocalizedString());
  }
}
项目:miku    文件:ExoPlayerImpl.java   
/**
 * Constructs an instance. Must be invoked from a thread that has an associated {@link Looper}.
 *
 * @param rendererCount The number of {@link TrackRenderer}s that will be passed to
 *     {@link #prepare(TrackRenderer[])}.
 * @param minBufferMs A minimum duration of data that must be buffered for playback to start
 *     or resume following a user action such as a seek.
 * @param minRebufferMs A minimum duration of data that must be buffered for playback to resume
 *     after a player invoked rebuffer (i.e. a rebuffer that occurs due to buffer depletion, and
 *     not due to a user action such as starting playback or seeking).
 */
@SuppressLint("HandlerLeak")
public ExoPlayerImpl(int rendererCount, int minBufferMs, int minRebufferMs) {
  Log.i(TAG, "Init " + ExoPlayerLibraryInfo.VERSION);
  this.playWhenReady = false;
  this.playbackState = STATE_IDLE;
  this.listeners = new CopyOnWriteArraySet<>();
  this.rendererHasMediaFlags = new boolean[rendererCount];
  this.rendererEnabledFlags = new boolean[rendererCount];
  for (int i = 0; i < rendererEnabledFlags.length; i++) {
    rendererEnabledFlags[i] = true;
  }
  eventHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      ExoPlayerImpl.this.handleEvent(msg);
    }
  };
  internalPlayer = new ExoPlayerImplInternal(eventHandler, playWhenReady, rendererEnabledFlags,
      minBufferMs, minRebufferMs);
}
项目:cot-java-rest-sdk    文件:SmartCepConnector.java   
/**
 * Subscribe to a notification channel. Will take effect immediately, even for currently running connect requests.
 * <br>
 * Subscribing to the same channel twice will just add any additional X-Ids.
 *
 * @param channel the name of the channel. No wildcards are allowed for SmartREST.
 * @param additionalXIds additionalXIds that are to be registered for this channel.
 */
public void subscribe(String channel, Set<String> additionalXIds) {
    // Wildcards in channel names are not supported by SmartREST:
    if (channel == null || channel.contains("*")) {
        throw new CotSdkException("Invalid channel name '"+channel+"'");
    }
    Set<String> xIds = subscriptions.get(channel);
    if (xIds == null) {
        xIds = new CopyOnWriteArraySet<>();
        subscriptions.put(channel, xIds);
    }
    if (additionalXIds != null) {
        xIds.addAll(additionalXIds);
    }

    // If we already have a clientId we should immediately send the subscribe request:
    if (clientId != null) {
        SmartRequest smartRequest = new SmartRequest(
                xId,
                MSG_REALTIME_SUBSCRIBE +
                  "," + clientId +
                  "," + channel +
                  (xIds.isEmpty() ? "" : "," + String.join(",", xIds)));
        cloudOfThingsRestClient.doSmartRealTimeRequest(smartRequest);
    }
}
项目:K-Sonic    文件:ExoPlayerImpl.java   
/**
 * Constructs an instance. Must be called from a thread that has an associated {@link Looper}.
 *
 * @param renderers The {@link Renderer}s that will be used by the instance.
 * @param trackSelector The {@link TrackSelector} that will be used by the instance.
 * @param loadControl The {@link LoadControl} that will be used by the instance.
 */
@SuppressLint("HandlerLeak")
public ExoPlayerImpl(Renderer[] renderers, TrackSelector trackSelector, LoadControl loadControl) {
  Log.i(TAG, "Init " + ExoPlayerLibraryInfo.VERSION + " [" + Util.DEVICE_DEBUG_INFO + "]");
  Assertions.checkState(renderers.length > 0);
  this.renderers = Assertions.checkNotNull(renderers);
  this.trackSelector = Assertions.checkNotNull(trackSelector);
  this.playWhenReady = false;
  this.playbackState = STATE_IDLE;
  this.listeners = new CopyOnWriteArraySet<>();
  emptyTrackSelections = new TrackSelectionArray(new TrackSelection[renderers.length]);
  timeline = Timeline.EMPTY;
  window = new Timeline.Window();
  period = new Timeline.Period();
  trackGroups = TrackGroupArray.EMPTY;
  trackSelections = emptyTrackSelections;
  eventHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      ExoPlayerImpl.this.handleEvent(msg);
    }
  };
  playbackInfo = new ExoPlayerImplInternal.PlaybackInfo(0, 0);
  internalPlayer = new ExoPlayerImplInternal(renderers, trackSelector, loadControl, playWhenReady,
      eventHandler, playbackInfo, this);
}
项目:aidl2    文件:ConcreteSetTypeArgsAndTypeLoss$$AidlClientImpl.java   
@Override
public <Y extends Serializable & Parcelable> HashSet<? extends X> methodWithCOWArraySetParamAndHashSetReturn(CopyOnWriteArraySet<Y> objectList) throws RemoteException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(ConcreteSetTypeArgsAndTypeLoss$$AidlServerImpl.DESCRIPTOR);

        if (objectList == null) {
            data.writeInt(-1);
        } else {
            data.writeInt(objectList.size());
            for (Parcelable objectListElement : objectList) {
                data.writeParcelable(objectListElement, 0);
            }
        }

        delegate.transact(ConcreteSetTypeArgsAndTypeLoss$$AidlServerImpl.TRANSACT_methodWithCOWArraySetParamAndHashSetReturn, data, reply, 0);
        reply.readException();

        return AidlUtil.readFromObjectStream(reply);
    } finally {
        data.recycle();
        reply.recycle();
    }
}