java.util.concurrent.CopyOnWriteArraySet Java Examples
The following examples show how to use
java.util.concurrent.CopyOnWriteArraySet.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SubscriberRegistry.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * 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 } }
Example #2
Source File: DelegatingDnsResolverTest.java From ibm-cos-sdk-java with Apache License 2.0 | 6 votes |
@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); }
Example #3
Source File: RxBus.java From RxBus with Apache License 2.0 | 6 votes |
public <T> void registerSubscriber(@NonNull Object observer, @NonNull CustomSubscriber<T> subscriber) { ObjectHelper.requireNonNull(observer, "Observer to register must not be null."); ObjectHelper.requireNonNull(subscriber, "Subscriber to register must not be null."); SUBSCRIBERS.putIfAbsent(observer.getClass(), new CopyOnWriteArraySet<CustomSubscriber<?>>()); Set<CustomSubscriber<?>> subscribers = SUBSCRIBERS.get(observer.getClass()); if (subscribers.contains(subscriber)) throw new IllegalArgumentException("Subscriber has already been registered."); else subscribers.add(subscriber); Observable<T> observable = bus.ofType(subscriber.getEventClass()) .observeOn(subscriber.getScheduler() == null ? AndroidSchedulers.mainThread() : subscriber.getScheduler()); Class<?> observerClass = observer.getClass(); OBSERVERS.putIfAbsent(observerClass, new CompositeDisposable()); CompositeDisposable composite = OBSERVERS.get(observerClass); composite.add(((subscriber.getFilter() == null) ? observable : observable.filter(subscriber.getFilter())) .subscribe(subscriber)); }
Example #4
Source File: AwsXRayIdsGeneratorTest.java From opentelemetry-java with Apache License 2.0 | 6 votes |
@Test public void shouldGenerateUniqueIdsInMultithreadedEnvironment() throws BrokenBarrierException, InterruptedException { AwsXRayIdsGenerator generator = new AwsXRayIdsGenerator(); Set<TraceId> traceIds = new CopyOnWriteArraySet<>(); Set<SpanId> spanIds = new CopyOnWriteArraySet<>(); int threads = 8; int generations = 128; CyclicBarrier barrier = new CyclicBarrier(threads + 1); Executor executor = Executors.newFixedThreadPool(threads); for (int i = 0; i < threads; i++) { executor.execute(new GenerateRunner(generations, generator, barrier, traceIds, spanIds)); } barrier.await(); barrier.await(); assertThat(traceIds).hasSize(threads * generations); assertThat(spanIds).hasSize(threads * generations); }
Example #5
Source File: CacheWatchRepairable.java From commons-jcs with Apache License 2.0 | 6 votes |
/** * Adds a feature to the CacheListener attribute of the CacheWatchRepairable object * <p> * @param cacheName The feature to be added to the CacheListener attribute * @param obj The feature to be added to the CacheListener attribute * @throws IOException */ @Override public <K, V> void addCacheListener( String cacheName, ICacheListener<K, V> obj ) throws IOException { // Record the added cache listener locally, regardless of whether the // remote add-listener operation succeeds or fails. Set<ICacheListener<?, ?>> listenerSet = cacheMap.computeIfAbsent(cacheName, key -> { return new CopyOnWriteArraySet<>(); }); listenerSet.add( obj ); log.info( "Adding listener to cache watch. ICacheListener = {0} | " + "ICacheObserver = {1} | cacheName = {2}", obj, cacheWatch, cacheName ); cacheWatch.addCacheListener( cacheName, obj ); }
Example #6
Source File: SettingConfig.java From Alice-LiveMan with GNU Affero General Public License v3.0 | 6 votes |
@Bean public LiveManSetting getLiveManSetting() throws Exception { LiveManSetting liveManSetting; if (settingFile.exists()) { liveManSetting = readSetting(); if (liveManSetting.getServers() == null) { liveManSetting.setServers(new CopyOnWriteArraySet<>()); } if (liveManSetting.getExternalAppSecretDOS() == null) { liveManSetting.setExternalAppSecretDOS(new CopyOnWriteArraySet<>()); } } else { liveManSetting = new LiveManSetting(); liveManSetting.setAccounts(new CopyOnWriteArraySet<>()); liveManSetting.setChannels(new CopyOnWriteArraySet<>()); liveManSetting.setServers(new CopyOnWriteArraySet<>()); liveManSetting.setExternalAppSecretDOS(new CopyOnWriteArraySet<>()); liveManSetting.setBannedKeywords(new String[0]); liveManSetting.setBannedYoutubeChannel(new String[0]); liveManSetting.setTempPath("liveManTemp"); saveSetting(liveManSetting); } return liveManSetting; }
Example #7
Source File: CopyOnWriteArraySetTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * 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); }
Example #8
Source File: AttributesFactory.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
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); }
Example #9
Source File: FragmentAPI.java From sa-sdk-android with Apache License 2.0 | 6 votes |
@Override public void enableAutoTrackFragment(Class<?> fragment) { try { if (fragment == null) { return; } if (mAutoTrackFragments == null) { mAutoTrackFragments = new CopyOnWriteArraySet<>(); } String canonicalName = fragment.getCanonicalName(); if (!TextUtils.isEmpty(canonicalName)) { mAutoTrackFragments.add(canonicalName.hashCode()); } } catch (Exception ex) { SALog.printStackTrace(ex); } }
Example #10
Source File: DefaultEventBus.java From sofa-registry with Apache License 2.0 | 6 votes |
/** * Post. * * @param event the event */ @Override public void post(final Event event) { if (!isEnable()) { return; } CopyOnWriteArraySet<EventSubscriber> subscribers = eventSubscriberMap.get(event.getClass()); if (null != subscribers && !subscribers.isEmpty()) { for (final EventSubscriber subscriber : subscribers) { if (subscriber.isSync()) { handleEvent(subscriber, event); } else { // 异步 executor.execute(new Runnable() { @Override public void run() { handleEvent(subscriber, event); } }); } } } }
Example #11
Source File: DefaultGroovyMethodsSupport.java From groovy with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") protected static <T> Set<T> createSimilarSet(Set<T> orig) { if (orig instanceof SortedSet) { Comparator comparator = ((SortedSet) orig).comparator(); if (orig instanceof ConcurrentSkipListSet) { return new ConcurrentSkipListSet<T>(comparator); } else { return new TreeSet<T>(comparator); } } else { if (orig instanceof CopyOnWriteArraySet) { return new CopyOnWriteArraySet<T>(); } else { // Do not use HashSet return new LinkedHashSet<T>(); } } }
Example #12
Source File: SubscriberRegistry.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * 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 } }
Example #13
Source File: AbstractConnectionListener.java From ironjacamar with Eclipse Public License 1.0 | 6 votes |
/** * Constructor * @param cm The connection manager * @param mc The managed connection * @param credential The credential * @param mcp The ManagedConnectionPool * @param flushStrategy The FlushStrategy */ public AbstractConnectionListener(ConnectionManager cm, ManagedConnection mc, Credential credential, ManagedConnectionPool mcp, FlushStrategy flushStrategy) { this.cm = cm; this.mc = mc; this.mcp = mcp; this.flushStrategy = flushStrategy; this.credential = credential; this.state = new AtomicInteger(FREE); this.connectionHandles = new CopyOnWriteArraySet<Object>(); if (cm.getConnectionManagerConfiguration().isTracking() != null && cm.getConnectionManagerConfiguration().isTracking().booleanValue()) this.connectionTraces = new HashMap<Object, Exception>(); long timestamp = System.currentTimeMillis(); this.validated = timestamp; this.fromPool = timestamp; this.toPool = timestamp; mc.addConnectionEventListener(this); }
Example #14
Source File: CglibCopierTest.java From Copiers with Apache License 2.0 | 6 votes |
@Test public void copySetTest() { Teacher teacher = newTeacher(); Set<Teacher> teachers = newHashSet(teacher, teacher); Set<TeacherEntity> targets = copier.copySet(teachers); for (TeacherEntity target : targets) { // 名称不同 assertThat(target.getUsername()).isNull(); assertThat(target.getAge()).isEqualTo(teacher.getAge()); assertThat(target.getSex()).isEqualTo(teacher.getSex()); assertThat(target.getHeight()).isEqualTo(teacher.getHeight()); // 类型不同 assertThat(target.getWeight()).isNull(); assertThat(target.getHandsome()).isEqualTo(teacher.getHandsome()); assertThat(target.getHouse()).isEqualTo(teacher.getHouse()); // 类型不同 assertThat(target.getLover()).isNull(); // 这里解释一下为什么相等,因为两个字段名称相同且类型都为 list assertThat(target.getStudents()).isEqualTo(teacher.getStudents()); } // 简单测试一下 copier.copySet(teachers, LinkedHashSet::new); copier.copySet(teachers, CopyOnWriteArraySet::new); copier.copySet(teachers, ConcurrentSkipListSet::new); }
Example #15
Source File: DeviceHiveWebSocketHandler.java From devicehive-java-server with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { CopyOnWriteArraySet<SubscriptionInfo> commandSubscriptions = (CopyOnWriteArraySet) session.getAttributes().get(CommandHandlers.SUBSCRIPTION_SET_NAME); commandService.sendUnsubscribeRequest(commandSubscriptions.stream() .map(SubscriptionInfo::getSubscriptionId).collect(Collectors.toSet())); CopyOnWriteArraySet<SubscriptionInfo> notificationSubscriptions = (CopyOnWriteArraySet) session.getAttributes().get(NotificationHandlers.SUBSCRIPTION_SET_NAME); notificationService.unsubscribe(notificationSubscriptions.stream() .map(SubscriptionInfo::getSubscriptionId).collect(Collectors.toSet())); sessionMonitor.removeSession(session.getId()); if(session.isOpen()) { session.close(); } logger.info("Websocket Connection Closed: session id {}, close status is {} ", session.getId(), status); }
Example #16
Source File: SubscriberRegistry.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * 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()); }
Example #17
Source File: SubscriberRegistry.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * 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()); }
Example #18
Source File: ExternalAppSecretBOImpl.java From Alice-LiveMan with GNU Affero General Public License v3.0 | 5 votes |
@Override public List<ExternalAppSecretDO> selectForList() { CopyOnWriteArraySet<ExternalAppSecretDO> externalAppSecretDOS = liveManSetting.getExternalAppSecretDOS(); if (liveManSetting.getExternalAppSecretDOS() == null) { return new ArrayList<>(); } else { return new ArrayList<>(externalAppSecretDOS); } }
Example #19
Source File: DownloadManager.java From Telegram-FOSS with GNU General Public License v2.0 | 5 votes |
/** * Constructs a {@link DownloadManager}. * * @param context Any context. * @param downloadIndex The download index used to hold the download information. * @param downloaderFactory A factory for creating {@link Downloader}s. */ public DownloadManager( Context context, WritableDownloadIndex downloadIndex, DownloaderFactory downloaderFactory) { this.context = context.getApplicationContext(); this.downloadIndex = downloadIndex; maxParallelDownloads = DEFAULT_MAX_PARALLEL_DOWNLOADS; minRetryCount = DEFAULT_MIN_RETRY_COUNT; downloadsPaused = true; downloads = Collections.emptyList(); listeners = new CopyOnWriteArraySet<>(); @SuppressWarnings("methodref.receiver.bound.invalid") Handler mainHandler = Util.createHandler(this::handleMainMessage); this.mainHandler = mainHandler; HandlerThread internalThread = new HandlerThread("DownloadManager file i/o"); internalThread.start(); internalHandler = new InternalHandler( internalThread, downloadIndex, downloaderFactory, mainHandler, maxParallelDownloads, minRetryCount, downloadsPaused); @SuppressWarnings("methodref.receiver.bound.invalid") RequirementsWatcher.Listener requirementsListener = this::onRequirementsStateChanged; this.requirementsListener = requirementsListener; requirementsWatcher = new RequirementsWatcher(context, requirementsListener, DEFAULT_REQUIREMENTS); notMetRequirements = requirementsWatcher.start(); pendingMessages = 1; internalHandler .obtainMessage(MSG_INITIALIZE, notMetRequirements, /* unused */ 0) .sendToTarget(); }
Example #20
Source File: HostTable.java From lams with GNU General Public License v2.0 | 5 votes |
public synchronized HostTable addHost(H host) { if(hosts.containsKey(host)) { throw UndertowMessages.MESSAGES.hostAlreadyRegistered(host); } hosts.put(host, new CopyOnWriteArraySet<Target>()); return this; }
Example #21
Source File: AbstractMediaRouteController.java From delion with Apache License 2.0 | 5 votes |
protected AbstractMediaRouteController() { mContext = ContextUtils.getApplicationContext(); assert (getContext() != null); mHandler = new Handler(); mMediaRouteSelector = buildMediaRouteSelector(); MediaRouter mediaRouter; try { // Pre-MR1 versions of JB do not have the complete MediaRouter APIs, // so getting the MediaRouter instance will throw an exception. mediaRouter = MediaRouter.getInstance(getContext()); } catch (NoSuchMethodError e) { Log.e(TAG, "Can't get an instance of MediaRouter, casting is not supported." + " Are you still on JB (JVP15S)?"); mediaRouter = null; } mMediaRouter = mediaRouter; mAvailableRouteListeners = new HashSet<MediaStateListener>(); // TODO(aberent): I am unclear why this is accessed from multiple threads, but // if I make it a HashSet then it gets ConcurrentModificationExceptions on some // types of disconnect. Investigate and fix. mUiListeners = new CopyOnWriteArraySet<UiListener>(); mDeviceDiscoveryCallback = new DeviceDiscoveryCallback(); mDeviceSelectionCallback = new DeviceSelectionCallback(); }
Example #22
Source File: SubscriberRegistry.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * 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()); }
Example #23
Source File: EventBus.java From gimBUS with MIT License | 5 votes |
/** * Call to register all event handlers for subscriber. */ public void register(@NonNull Object subscriber) { assignThreadForSubscriber(subscriber); //Key: the event class to handle //Value: set of event handlers that can handle this event class. for (Map.Entry<Class<?>, List<EventHandler>> entry : Cache.findAllEventHandlersForSubscriber(subscriber).entrySet()) { Class<?> eventType = entry.getKey(); CopyOnWriteArraySet<EventHandler> registeredEventHandlersForEventType = mRegisteredEventHandlersByEventType.get(eventType); //If there is no Set of EventHandlers for this type of event, we have to create one. But it must be safe, no race condition, thus synchronized(). if (registeredEventHandlersForEventType == null) { synchronized (mRegisteredEventHandlersByEventType) { //check again, maybe other thread managed to add the Set already, while this one waied for the synchronization registeredEventHandlersForEventType = mRegisteredEventHandlersByEventType.get(eventType); if (registeredEventHandlersForEventType == null) { registeredEventHandlersForEventType = new CopyOnWriteArraySet<>(); mRegisteredEventHandlersByEventType.put(eventType, registeredEventHandlersForEventType); } } } //finally, add new event handlers to the registered handlers registeredEventHandlersForEventType.addAll(entry.getValue()); Object stickyEvent = Cache.stickyEvents.get(entry.getKey()); if (stickyEvent != null) { sendTo(stickyEvent, subscriber); } } }
Example #24
Source File: EventBus.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * 注册一个订阅者 * * @param eventClass 事件类型 * @param subscriber 订阅者 */ public static void register(Class<? extends Event> eventClass, Subscriber subscriber) { CopyOnWriteArraySet<Subscriber> set = SUBSCRIBER_MAP.get(eventClass); if (set == null) { set = new CopyOnWriteArraySet<Subscriber>(); CopyOnWriteArraySet<Subscriber> old = SUBSCRIBER_MAP.putIfAbsent(eventClass, set); if (old != null) { set = old; } } set.add(subscriber); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Register subscriber: {} of event: {}.", subscriber, eventClass); } }
Example #25
Source File: SentinelConfigLoader.java From Sentinel with Apache License 2.0 | 5 votes |
private static void load() { // Order: system property -> system env -> default file (classpath:sentinel.properties) -> legacy path String fileName = System.getProperty(SENTINEL_CONFIG_PROPERTY_KEY); if (StringUtil.isBlank(fileName)) { fileName = System.getenv(SENTINEL_CONFIG_ENV_KEY); if (StringUtil.isBlank(fileName)) { fileName = DEFAULT_SENTINEL_CONFIG_FILE; } } Properties p = ConfigUtil.loadProperties(fileName); if (p != null && !p.isEmpty()) { RecordLog.info("[SentinelConfigLoader] Loading Sentinel config from " + fileName); properties.putAll(p); } for (Map.Entry<Object, Object> entry : new CopyOnWriteArraySet<>(System.getProperties().entrySet())) { String configKey = entry.getKey().toString(); String newConfigValue = entry.getValue().toString(); String oldConfigValue = properties.getProperty(configKey); properties.put(configKey, newConfigValue); if (oldConfigValue != null) { RecordLog.info("[SentinelConfigLoader] JVM parameter overrides {}: {} -> {}", configKey, oldConfigValue, newConfigValue); } } }
Example #26
Source File: AnalyticsCollector.java From Telegram with GNU General Public License v2.0 | 5 votes |
/** * Creates an analytics collector for the specified player. * * @param player The {@link Player} for which data will be collected. Can be null, if the player * is set by calling {@link AnalyticsCollector#setPlayer(Player)} before using the analytics * collector. * @param clock A {@link Clock} used to generate timestamps. */ protected AnalyticsCollector(@Nullable Player player, Clock clock) { if (player != null) { this.player = player; } this.clock = Assertions.checkNotNull(clock); listeners = new CopyOnWriteArraySet<>(); mediaPeriodQueueTracker = new MediaPeriodQueueTracker(); window = new Window(); }
Example #27
Source File: MockLite.java From httplite with Apache License 2.0 | 5 votes |
MockLite(MockHandler handler, ObjectParser parser, ExecutorService executor, HttpLite lite) { this.handler = handler; this.parser = parser; this.executor = executor; this.tasks = new CopyOnWriteArraySet<>(); this.lite = lite; }
Example #28
Source File: EventAdminServiceImpl.java From sofa-ark with Apache License 2.0 | 5 votes |
@Override public void register(EventHandler eventHandler) { CopyOnWriteArraySet<EventHandler> set = SUBSCRIBER_MAP.get(eventHandler.getClass() .getClassLoader()); if (set == null) { set = new CopyOnWriteArraySet<>(); CopyOnWriteArraySet<EventHandler> old = SUBSCRIBER_MAP.putIfAbsent(eventHandler .getClass().getClassLoader(), set); if (old != null) { set = old; } } set.add(eventHandler); LOGGER.debug(String.format("Register event handler: %s.", eventHandler)); }
Example #29
Source File: CopyOnWriteArraySetTest.java From j2objc with Apache License 2.0 | 5 votes |
static CopyOnWriteArraySet<Integer> populatedSet(int n) { CopyOnWriteArraySet<Integer> a = new CopyOnWriteArraySet<Integer>(); assertTrue(a.isEmpty()); for (int i = 0; i < n; i++) a.add(i); assertEquals(n == 0, a.isEmpty()); assertEquals(n, a.size()); return a; }
Example #30
Source File: EventService.java From che with Eclipse Public License 2.0 | 5 votes |
private void doSubscribe(EventSubscriber<?> subscriber, Class<?> eventType) { Set<EventSubscriber> entries = subscribersByEventType.get(eventType); if (entries == null) { Set<EventSubscriber> newEntries = new CopyOnWriteArraySet<>(); entries = subscribersByEventType.putIfAbsent(eventType, newEntries); if (entries == null) { entries = newEntries; } } entries.add(subscriber); }