Java Code Examples for java.util.concurrent.CopyOnWriteArrayList#size()

The following examples show how to use java.util.concurrent.CopyOnWriteArrayList#size() . 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: SdlSession2.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void stopStream(SessionType serviceType) {
    if(SessionType.NAV.equals(serviceType)){
        stopVideoStream();
    }else if(SessionType.PCM.equals(serviceType)){
        stopAudioStream();
    }
    // Notify any listeners of the service being ended
    if(serviceListeners != null && serviceListeners.containsKey(serviceType)){
        CopyOnWriteArrayList<ISdlServiceListener> listeners = serviceListeners.get(serviceType);
        if (listeners != null && listeners.size() > 0) {
            for (ISdlServiceListener listener : listeners) {
                listener.onServiceEnded(this, serviceType);
            }
        }
    }
}
 
Example 2
Source File: TopicLogic.java    From fingerpoetry-android with Apache License 2.0 6 votes vote down vote up
private void initDefaultTopics() {
    // 1.Sysconfig default topics
    CopyOnWriteArrayList<Topic> tmp = SystemLogic.getInstance().getDefaultTopics();
    if (tmp.size() > 0) {
        this.defaultTopics = tmp;
    } else {
        //  2.raw default topics
        Resources resources = BookBoxApplication.getInstance().getResources();
        InputStream in = resources.openRawResource(R.raw.topics);
        String data = FileUtils.readInStream(in);
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotEmpty(data)) {
            ArrayList<Topic> defaults = fromJsonList(data, Topic.class);
            Timber.i("get topics from raw.");
            this.defaultTopics = new CopyOnWriteArrayList<>(defaults);
        }
    }
    updateDefaultTopicStatus();
}
 
Example 3
Source File: ScriptDataController.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/showStatus")
private List<RobotInfo> showStatus(String ip) throws IOException {

    //托管机器人
    String s = HttpUtilManager.getInstance()
            .requestHttpGet("http://" + ip + ":8080/common-core/v1/jsexcutor/list", null, MapBuilder.build());
    if (s == null) {
        return null;
    }
    JsonNode jsonNode = JSONUtils.buildJsonNode(s);
    JsonNode jsonNode1 = jsonNode.get("data");

    CopyOnWriteArrayList<RobotInfo> list = new CopyOnWriteArrayList<>();
    for (JsonNode node : jsonNode1) {
        Boolean running = node.get("running").asBoolean();
        if (running) {
            RobotInfo robotInfo = new RobotInfo();
            robotInfo.setTid(node.get("tId").asText());
            robotInfo.setId(node.get("script").get("ipAndScriptId").asText());
            list.add(robotInfo);
        }
    }
    if (0 < list.size()) ListIPAndScrpit.get(ip).setRobotInfoList(list);
    return list;
}
 
Example 4
Source File: LifecycleManager.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean onRPCReceived(final RPCMessage message){
    synchronized(RPC_LISTENER_LOCK){
        if(message == null || message.getFunctionID() == null){
            return false;
        }

        final int id = message.getFunctionID().getId();
        CopyOnWriteArrayList<OnRPCListener> listeners = rpcListeners.get(id);
        if(listeners!=null && listeners.size()>0) {
            for (OnRPCListener listener : listeners) {
                listener.onReceived(message);
            }
            return true;
        }
        return false;
    }
}
 
Example 5
Source File: DictionaryCollection.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final ComposedData composedData,
        final NgramContext ngramContext, final long proximityInfoHandle,
        final SettingsValuesForSuggestion settingsValuesForSuggestion,
        final int sessionId, final float weightForLocale,
        final float[] inOutWeightOfLangModelVsSpatialModel) {
    final CopyOnWriteArrayList<Dictionary> dictionaries = mDictionaries;
    if (dictionaries.isEmpty()) return null;
    // To avoid creating unnecessary objects, we get the list out of the first
    // dictionary and add the rest to it if not null, hence the get(0)
    ArrayList<SuggestedWordInfo> suggestions = dictionaries.get(0).getSuggestions(composedData,
            ngramContext, proximityInfoHandle, settingsValuesForSuggestion, sessionId,
            weightForLocale, inOutWeightOfLangModelVsSpatialModel);
    if (null == suggestions) suggestions = new ArrayList<>();
    final int length = dictionaries.size();
    for (int i = 1; i < length; ++ i) {
        final ArrayList<SuggestedWordInfo> sugg = dictionaries.get(i).getSuggestions(
                composedData, ngramContext, proximityInfoHandle, settingsValuesForSuggestion,
                sessionId, weightForLocale, inOutWeightOfLangModelVsSpatialModel);
        if (null != sugg) suggestions.addAll(sugg);
    }
    return suggestions;
}
 
Example 6
Source File: X8sPanelRecycleAdapter.java    From FimiX8-RE with MIT License 5 votes vote down vote up
public void updateDeleteItem(int position) {
    MediaModel mediaModel = (MediaModel) this.modelList.get(position);
    if (mediaModel != null) {
        String formateDate = mediaModel.getFormatDate();
        String localPath = mediaModel.getFileLocalPath();
        this.modelList.remove(position);
        statisticalFileCount(mediaModel, false);
        notifyItemRemoved(position);
        if (!(this.stateHashMap == null || localPath == null)) {
            CopyOnWriteArrayList<T> internalList = (CopyOnWriteArrayList) this.stateHashMap.get(formateDate.split(" ")[0]);
            if (internalList != null) {
                Iterator it = internalList.iterator();
                while (it.hasNext()) {
                    MediaModel cacheModel = (MediaModel) it.next();
                    if (cacheModel != null && localPath.equals(cacheModel.getFileLocalPath())) {
                        internalList.remove(cacheModel);
                    }
                }
                if (internalList.size() < this.internalListBound) {
                    if (internalList.size() < this.internalListBound) {
                        if (position - 1 < this.modelList.size()) {
                            this.modelList.remove(position - 1);
                            notifyItemRemoved(position - 1);
                            notifyItemRangeRemoved(position, this.modelList.size() - position);
                        } else {
                            this.modelList.remove(this.modelList.size() - 1);
                            notifyItemRemoved(this.modelList.size() - 1);
                        }
                    }
                    judgeIsNoData();
                    return;
                }
            }
        }
        judgeIsNoData();
        notifyItemRangeRemoved(position, this.modelList.size() - position);
    }
}
 
Example 7
Source File: RedisApplication.java    From redis-admin with Apache License 2.0 5 votes vote down vote up
protected void initRedisKeysCache(RedisTemplate redisTemplate, String serverName , int dbIndex) {
	RedisConnection connection = RedisConnectionUtils.getConnection(redisTemplate.getConnectionFactory());
	connection.select(dbIndex);
	Set<byte[]> keysSet = connection.keys("*".getBytes());
	connection.close();
	List<RKey> tempList = new ArrayList<RKey>();
	ConvertUtil.convertByteToString(connection, keysSet, tempList);
	Collections.sort(tempList);
	CopyOnWriteArrayList<RKey> redisKeysList = new CopyOnWriteArrayList<RKey>(tempList);
	if(redisKeysList.size()>0) {
		redisKeysListMap.put(serverName+DEFAULT_SEPARATOR+dbIndex, redisKeysList);
	}
}
 
Example 8
Source File: XulSubscriberMethodHunter.java    From starcor.xul with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * remove subscriber methods from map
 */
public void removeMethodsFromMap(Object subscriber) {
    Iterator<CopyOnWriteArrayList<XulSubscription>> iterator =
            _subscriberMap.values().iterator();
    while (iterator.hasNext()) {
        CopyOnWriteArrayList<XulSubscription> subscriptions = iterator.next();
        if (subscriptions != null) {
            List<XulSubscription> foundSubscriptions = new LinkedList<XulSubscription>();
            Iterator<XulSubscription> subIterator = subscriptions.iterator();
            while (subIterator.hasNext()) {
                XulSubscription xulSubscription = subIterator.next();
                // 获取引用
                Object cacheObject = xulSubscription.getSubscriber();
                if ((cacheObject == null)
                    || cacheObject.equals(subscriber)) {
                    xulSubscription.clearXulMessages();
                    foundSubscriptions.add(xulSubscription);
                }
            }

            // 移除该subscriber的相关的Subscription
            subscriptions.removeAll(foundSubscriptions);
        }

        // 如果针对某个Msg的订阅者数量为空了,那么需要从map中清除
        if (subscriptions == null || subscriptions.size() == 0) {
            iterator.remove();
        }
    }
}
 
Example 9
Source File: ViewTreeObserver.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Notifies registered listeners that focus has changed.
 */
final void dispatchOnGlobalFocusChange(View oldFocus, View newFocus) {
    // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
    // perform the dispatching. The iterator is a safe guard against listeners that
    // could mutate the list by calling the various add/remove methods. This prevents
    // the array from being modified while we iterate it.
    final CopyOnWriteArrayList<OnGlobalFocusChangeListener> listeners = mOnGlobalFocusListeners;
    if (listeners != null && listeners.size() > 0) {
        for (OnGlobalFocusChangeListener listener : listeners) {
            listener.onGlobalFocusChanged(oldFocus, newFocus);
        }
    }
}
 
Example 10
Source File: SerializerPojo.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
public SerializerPojo(CopyOnWriteArrayList<ClassInfo> registered){
    if(registered == null)
        registered = new CopyOnWriteArrayList<ClassInfo>();
    this.registered = registered;
    oldSize = registered.size();
    for(int i=0;i<registered.size();i++)
    {
        ClassInfo ci = registered.get(i);
        Class clazz = classForName(ci.name);
        class2classId.put(clazz, i);
        classId2class.put(i, clazz);

    }
}
 
Example 11
Source File: ProxyBridge.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public boolean onRPCReceived(final RPCMessage message){
	synchronized(RPC_LISTENER_LOCK){
		final int id = FunctionID.getFunctionId(message.getFunctionName());
		CopyOnWriteArrayList<OnRPCListener> listeners = rpcListeners.get(id);
		if(listeners!=null && listeners.size()>0) {
			for (OnRPCListener listener : listeners) {
				listener.onReceived(message);
			}
			return true;
		}
		return false;
	}
}
 
Example 12
Source File: ObserverManagerImpl.java    From Cangol-appcore with Apache License 2.0 5 votes vote down vote up
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    final String event = subscriberMethod.event;

    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEvent.get(event);
    final Subscription newSubscription = new Subscription(subscriber, subscriberMethod, subscriberMethod.priority);

    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<>();
        subscriptionsByEvent.put(event, subscriptions);
    } else {
        for (final Subscription subscription : subscriptions) {
            if (subscription.equals(newSubscription)) {
                throw new IllegalArgumentException("Subscriber " + subscriber.getClass() + " already registered to event " + event);
            }
        }
    }

    final int size = subscriptions.size();
    for (int i = 0; i <= size; i++) {
        if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
            subscriptions.add(i, newSubscription);
            break;
        }
    }

    List<String> subscribedevents = eventBySubscriber.get(subscriber);
    if (subscribedevents == null) {
        subscribedevents = new ArrayList<>();
        eventBySubscriber.put(subscriber, subscribedevents);
    }
    subscribedevents.add(event);

}
 
Example 13
Source File: RandomStrategy.java    From rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public RPCChannelGroup.ChannelInfo selectChannel(CopyOnWriteArrayList<RPCChannelGroup> allConnections) {
    long totalHostCount = allConnections.size();
    if (totalHostCount == 0) {
        return null;
    }

    int index = (int) (getRandomLong() % totalHostCount);
    RPCChannelGroup channelGroup = allConnections.get(index);
    int subIndex = (int) (getRandomLong() % channelGroup.getConnectionNum());
    Channel channel = channelGroup.getChannel(subIndex);
    return new RPCChannelGroup.ChannelInfo(channelGroup, channel);
}
 
Example 14
Source File: SystemCapabilityManager.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Notifies listeners in the list about the new retrieved capability
 * @param systemCapabilityType the system capability type that was retrieved
 * @param capability the system capability value that was retrieved
 */
private void notifyListeners(SystemCapabilityType systemCapabilityType, Object capability) {
	synchronized(LISTENER_LOCK) {
		CopyOnWriteArrayList<OnSystemCapabilityListener> listeners = onSystemCapabilityListeners.get(systemCapabilityType);
		if (listeners != null && listeners.size() > 0) {
			for (OnSystemCapabilityListener listener : listeners) {
				listener.onCapabilityRetrieved(capability);
			}
		}
	}
}
 
Example 15
Source File: Device.java    From neatle with MIT License 5 votes vote down vote up
@Override
public int getCharacteristicsChangedListenerCount(UUID characteristicsUUID) {
    synchronized (lock) {
        CopyOnWriteArrayList<CharacteristicsChangedListener> list = changeListeners.get(characteristicsUUID);
        return list == null ? 0 : list.size();

    }
}
 
Example 16
Source File: SystemCapabilityManager.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Notifies listeners in the list about the new retrieved capability
 * @param systemCapabilityType the system capability type that was retrieved
 * @param capability the system capability value that was retrieved
 */
private void notifyListeners(SystemCapabilityType systemCapabilityType, Object capability) {
	synchronized(LISTENER_LOCK) {
		CopyOnWriteArrayList<OnSystemCapabilityListener> listeners = onSystemCapabilityListeners.get(systemCapabilityType);
		if (listeners != null && listeners.size() > 0) {
			for (OnSystemCapabilityListener listener : listeners) {
				listener.onCapabilityRetrieved(capability);
			}
		}
	}
}
 
Example 17
Source File: ListAccumulator.java    From Apache-Spark-2x-for-Java-Developers with MIT License 4 votes vote down vote up
public ListAccumulator(CopyOnWriteArrayList<Integer> value) {
	if (value.size() != 0) {
		accList = new CopyOnWriteArrayList<Integer>(value);
	}
}
 
Example 18
Source File: ScheduleJobs.java    From ProxyPool with Apache License 2.0 4 votes vote down vote up
/**
 * 每隔几个小时跑一次任务
 */
@Scheduled(cron="${cronJob.schedule}")
public void cronJob() {

    //1.检查job的状态
    checkRunningStat();

    log.info("Job Start...");

    //2.获取目标网页的Url
    ProxyPool.proxyMap = proxyDao.getProxyMap();

    //3.如果数据库里没取到,用默认内置的
    if(Preconditions.isBlank(ProxyPool.proxyMap)) {
        log.info("Job proxyDao.getProxyMap() is empty");
        ProxyPool.proxyMap = Constant.proxyMap;
    }

    //4.每次跑job先清空缓存中的内容
    if (cacheManager.getCache("proxys")!=null) {

        cacheManager.getCache("proxys").clear();
    }

    //5.创建一个日志对象,用于存储job的每次工作记录
    JobLog jobLog = new JobLog();
    jobLog.setJobName("ScheduleJobs.cronJob");
    jobLog.setStartTime(JodaUtils.formatDateTime(new Date()));

    //6.跑任务之前先清空proxyList中上一次job留下的proxy数据,
    ProxyPool.proxyList.clear();

    //7.从数据库中选取10个代理作为种子代理,遇到http 503时使用代理来抓数据
    ProxyPool.addProxyList(getProxyList(proxyDao.takeRandomTenProxy()));
    log.info("Job ProxyPool.proxyList size = "+ProxyPool.proxyList.size());
    //8.正式开始,爬代理数据
    proxyManager.start();

    //9.爬完以后,把数据转换为ProxyData并存到数据库
    CopyOnWriteArrayList<ProxyData> list = getProxyDataList(ProxyPool.proxyList);
    log.info("Job ProxyData list size = "+list.size());
    if (Preconditions.isNotBlank(list)) {

        // 10. list的数量<=15时,不删除数据库里的老数据
        if (list.size()>15) {
            proxyDao.deleteAll();
            log.info("Job after deleteAll");
        }

        //11. 然后再进行插入新的proxy
        for (ProxyData p:list) {
            proxyDao.saveProxy(p);
        }
        log.info("Job save count = "+list.size());

        jobLog.setResultDesc(String.format("success save count = %s", list.size()));
        jobLog.setEndTime(JodaUtils.formatDateTime(new Date()));
        commonDao.saveJobLog(jobLog);

    } else {
        log.info("Job proxyList is empty...");
    }

    //12. 设置job状态为停止
    stop();

    log.info("Job End...");
}
 
Example 19
Source File: BaseRecycleAdapter.java    From FimiX8-RE with MIT License 4 votes vote down vote up
public void addItemReally(T mediaModel) {
    int inserterPosition = 0;
    if (mediaModel != null) {
        this.modelNoHeadList.add(mediaModel);
        String currentFormatData = mediaModel.getFormatDate();
        if (this.stateHashMap.containsKey(currentFormatData)) {
            CopyOnWriteArrayList internalList = (CopyOnWriteArrayList) this.stateHashMap.get(currentFormatData);
            if (internalList.size() > 0) {
                int position = this.modelList.indexOf(internalList.get(0));
                internalList.add(mediaModel);
                this.modelList.add(position + 1, mediaModel);
            }
        } else {
            CopyOnWriteArrayList newList = new CopyOnWriteArrayList();
            int forEachPosition = 0;
            for (Entry<String, CopyOnWriteArrayList<T>> entry : this.stateHashMap.entrySet()) {
                forEachPosition++;
                if (currentFormatData.compareTo((String) entry.getKey()) <= 0) {
                    break;
                }
                inserterPosition += ((CopyOnWriteArrayList) entry.getValue()).size();
            }
            MediaModel mediaModel1;
            if (forEachPosition == 1) {
                mediaModel1 = new MediaModel();
                mediaModel1.setCategory(true);
                mediaModel1.setFormatDate(mediaModel.getFormatDate());
                newList.add(mediaModel1);
                newList.add(mediaModel);
                this.modelList.add(mediaModel1);
                this.modelList.add(mediaModel);
            } else {
                mediaModel1 = new MediaModel();
                mediaModel1.setCategory(true);
                mediaModel1.setFormatDate(mediaModel.getFormatDate());
                newList.add(mediaModel1);
                newList.add(mediaModel);
                this.modelList.add(inserterPosition, mediaModel1);
                this.modelList.add(inserterPosition + 1, mediaModel);
            }
            this.stateHashMap.put(currentFormatData, newList);
        }
    }
    Message message = Message.obtain();
    message.what = 7;
    message.arg1 = inserterPosition;
    this.mainHandler.sendMessage(message);
}
 
Example 20
Source File: FileCommitLogTest.java    From herddb with Apache License 2.0 4 votes vote down vote up
@Test
public void testMaxBatchSizeBytes() throws Exception {
    TestStatsProvider testStatsProvider = new TestStatsProvider();
    TestStatsProvider.TestStatsLogger statsLogger = testStatsProvider.getStatsLogger("test");

    try (FileCommitLogManager manager = new FileCommitLogManager(
            folder.newFolder().toPath(),
            ServerConfiguration.PROPERTY_MAX_LOG_FILE_SIZE_DEFAULT,
            Integer.MAX_VALUE, // no flush by batch size
            LogEntryFactory.beginTransaction(0).serialize().length * 2 - 1, // flush after 2 writes
            Integer.MAX_VALUE, // no flush by time
            true /* require fsync */,
            false, /* O_DIRECT */
            ServerConfiguration.PROPERTY_DEFERRED_SYNC_PERIOD_DEFAULT,
            statsLogger)) {
        manager.start();

        int writeCount = 0;
        final long _startWrite = System.currentTimeMillis();
        try (FileCommitLog log = manager.createCommitLog("tt", "aa", "nodeid")) {
            log.startWriting();
            CopyOnWriteArrayList<LogSequenceNumber> completed = new CopyOnWriteArrayList<>();

            CommitLogResult future = log.log(LogEntryFactory.beginTransaction(0), true);
            future.logSequenceNumber.thenAccept(completed::add);
            assertFalse(future.logSequenceNumber.isDone());

            CommitLogResult future2 = log.log(LogEntryFactory.beginTransaction(0), true);
            future2.logSequenceNumber.thenAccept(completed::add);

            future.logSequenceNumber.get(10, TimeUnit.SECONDS);
            future2.logSequenceNumber.get(10, TimeUnit.SECONDS);

            TestUtils.waitForCondition(() -> {
                return completed.size() == 2;
            }, NOOP, 100);

            writeCount = completed.size();

            assertTrue(completed.get(1).after(completed.get(0)));
        }
        final long _endWrite = System.currentTimeMillis();
        AtomicInteger readCount = new AtomicInteger();
        try (CommitLog log = manager.createCommitLog("tt", "aa", "nodeid")) {
            log.recovery(LogSequenceNumber.START_OF_TIME, new BiConsumer<LogSequenceNumber, LogEntry>() {
                @Override
                public void accept(LogSequenceNumber t, LogEntry u) {
                    readCount.incrementAndGet();
                }
            }, true);
        }
        final long _endRead = System.currentTimeMillis();
        assertEquals(writeCount, readCount.get());
        System.out.println("Write time: " + (_endWrite - _startWrite) + " ms");
        System.out.println("Read time: " + (_endRead - _endWrite) + " ms");
    }
}