下面列出了java.util.concurrent.CopyOnWriteArrayList#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
@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);
}
}
}
}
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;
}
}
@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;
}
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();
}
/**
* 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);
}
}
}
}
/**
* 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);
}
}
}
}
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);
}
}
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);
}
}
/**
* 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);
}
}
}
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;
}
}
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);
}
@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);
}
@Override
public int getCharacteristicsChangedListenerCount(UUID characteristicsUUID) {
synchronized (lock) {
CopyOnWriteArrayList<CharacteristicsChangedListener> list = changeListeners.get(characteristicsUUID);
return list == null ? 0 : list.size();
}
}
/**
* 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();
}
}
}
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);
}
}
@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");
}
}
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);
}
/**
* 每隔几个小时跑一次任务
*/
@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...");
}
public ListAccumulator(CopyOnWriteArrayList<Integer> value) {
if (value.size() != 0) {
accList = new CopyOnWriteArrayList<Integer>(value);
}
}