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

The following examples show how to use java.util.concurrent.CopyOnWriteArrayList#add() . 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: DatabaseBackend.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
public CopyOnWriteArrayList<Conversation> getConversations(int status) {
    CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    String[] selectionArgs = {Integer.toString(status)};
    Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
            + " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
            + Conversation.CREATED + " desc", selectionArgs);
    while (cursor.moveToNext()) {
        final Conversation conversation = Conversation.fromCursor(cursor);
        if (conversation.getJid() instanceof InvalidJid) {
            continue;
        }
        list.add(conversation);
    }
    cursor.close();
    return list;
}
 
Example 2
Source File: ConstructorInstrumenter.java    From allocation-instrumenter with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures that the given sampler will be invoked every time a constructor for class c is invoked.
 *
 * @param c The class to be tracked
 * @param sampler the code to be invoked when an instance of c is constructed
 * @throws UnmodifiableClassException if c cannot be modified.
 */
public static void instrumentClass(Class<?> c, ConstructorCallback<?> sampler)
    throws UnmodifiableClassException {
  // IMPORTANT: Don't forget that other threads may be accessing this
  // class while this code is running.  Specifically, the class may be
  // executed directly after the retransformClasses is called.  Thus, we need
  // to be careful about what happens after the retransformClasses call.
  synchronized (samplerPutAtomicityLock) {
    List<ConstructorCallback<?>> list = samplerMap.get(c);
    if (list == null) {
      CopyOnWriteArrayList<ConstructorCallback<?>> samplerList =
          new CopyOnWriteArrayList<ConstructorCallback<?>>();
      samplerList.add(sampler);
      samplerMap.put(c, samplerList);
      Instrumentation inst = AllocationRecorder.getInstrumentation();
      Class<?>[] cs = new Class<?>[1];
      cs[0] = c;
      inst.retransformClasses(c);
    } else {
      list.add(sampler);
    }
  }
}
 
Example 3
Source File: CopyOnWriteArrayListTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * lists with same elements are equal and have same hashCode
 */
public void testEquals() {
    CopyOnWriteArrayList a = populatedArray(3);
    CopyOnWriteArrayList b = populatedArray(3);
    assertTrue(a.equals(b));
    assertTrue(b.equals(a));
    assertTrue(a.containsAll(b));
    assertTrue(b.containsAll(a));
    assertEquals(a.hashCode(), b.hashCode());
    a.add(m1);
    assertFalse(a.equals(b));
    assertFalse(b.equals(a));
    assertTrue(a.containsAll(b));
    assertFalse(b.containsAll(a));
    b.add(m1);
    assertTrue(a.equals(b));
    assertTrue(b.equals(a));
    assertTrue(a.containsAll(b));
    assertTrue(b.containsAll(a));
    assertEquals(a.hashCode(), b.hashCode());

    assertFalse(a.equals(null));
}
 
Example 4
Source File: SocketController.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
/**
 * 收到客户端消息后调用的方法
 *
 * @param message 客户端发送过来的消息
 * @param mySession 可选的参数
 * @throws Exception
 */
@OnMessage
public void onMessage(String message,Session mySession) throws Exception {
    JsonNode jsonNode = JSONUtils.buildJsonNode(message);
    JsonNode sub = jsonNode.get("subscribe");
    if(null != sub) {
        String substr = jsonNode.get("subscribe").asText();
        if(null != substr && !"".equals(substr)) {
            CopyOnWriteArrayList<SocketSession> tmp = subscribeSession.get(substr);
            if(null == tmp) {
                tmp = new CopyOnWriteArrayList<>();
            }
            tmp.add( new SocketSession(substr, mySession));
            subscribeSession.put(substr,tmp);
        }
    }
}
 
Example 5
Source File: DingTalkJobProperty.java    From dingtalk-plugin with MIT License 6 votes vote down vote up
/**
 * 在配置页面展示的列表,需要跟 `全局配置` 同步机器人信息
 *
 * @return 机器人配置列表
 */
public CopyOnWriteArrayList<DingTalkNotifierConfig> getNotifierConfigs() {

  CopyOnWriteArrayList<DingTalkNotifierConfig> notifierConfigsList = new CopyOnWriteArrayList<>();
  CopyOnWriteArrayList<DingTalkRobotConfig> robotConfigs = DingTalkGlobalConfig.get()
      .getRobotConfigs();

  for (DingTalkRobotConfig robotConfig : robotConfigs) {
    String id = robotConfig.getId();
    DingTalkNotifierConfig newNotifierConfig = new DingTalkNotifierConfig(robotConfig);
    if (notifierConfigs != null && !notifierConfigs.isEmpty()) {
      for (DingTalkNotifierConfig notifierConfig : notifierConfigs) {
        String robotId = notifierConfig.getRobotId();
        if (id.equals(robotId) && notifierConfig.isChecked()) {
          newNotifierConfig.setChecked(true);
          newNotifierConfig.setAtMobile(notifierConfig.getAtMobile());
          newNotifierConfig.setContent(notifierConfig.getContent());
        }
      }
    }
    notifierConfigsList.add(newNotifierConfig);
  }

  return notifierConfigsList;
}
 
Example 6
Source File: StorageMappings.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public StorageMappings(ExternalStorageSources externalStorageSources) {
	for (Entry<StorageType, CopyOnWriteArrayList<ExternalStorageSource>> entry : externalStorageSources
			.entrySet()) {
		CopyOnWriteArrayList<StorageMapping> list = new CopyOnWriteArrayList<>();
		for (ExternalStorageSource externalStorageSource : entry.getValue()) {
			if (BooleanUtils.isTrue(externalStorageSource.getEnable())) {
				StorageMapping storageMapping = new StorageMapping(externalStorageSource);
				list.add(storageMapping);
			}
			this.put(entry.getKey(), list);
		}
	}
}
 
Example 7
Source File: Bus.java    From support with Apache License 2.0 5 votes vote down vote up
public void register(Object subscriber) {
    List<Method> methods = mFinder.findSubscriber(subscriber.getClass());
    if (methods == null || methods.size() < 1) {
        return;
    }
    CopyOnWriteArrayList<Subscriber> subscribers = mSubscriberMap.get(subscriber.getClass());
    if (subscribers == null) {
        subscribers = new CopyOnWriteArrayList<>();
        mSubscriberMap.put(methods.get(0).getParameterTypes()[0], subscribers);
    }
    for (Method method : methods) {
        Subscriber newSubscriber = new Subscriber(subscriber, method);
        subscribers.add(newSubscriber);
    }
}
 
Example 8
Source File: CopyOnWriteArrayListTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test that we don't retain the array returned by toArray() on the copy
 * constructor. That array may not be of the required type!
 */
public void testDoesNotRetainToArray() {
    String[] strings = { "a", "b", "c" };
    List<String> asList = Arrays.asList(strings);
    assertEquals(String[].class, asList.toArray().getClass());
    CopyOnWriteArrayList<Object> objects = new CopyOnWriteArrayList<Object>(asList);
    objects.add(Boolean.TRUE);
}
 
Example 9
Source File: Lists.java    From boon with Apache License 2.0 5 votes vote down vote up
public static <T> List<T> safeLazyAdd(CopyOnWriteArrayList<T> list, T... items) {
    list = list == null ? new CopyOnWriteArrayList<T>() : list;
    for (T item : items) {
        list.add(item);
    }
    return list;
}
 
Example 10
Source File: Lists.java    From boon with Apache License 2.0 5 votes vote down vote up
public static <T> List<T> lazyAdd(CopyOnWriteArrayList<T> list, T... items) {
    list = list == null ? new CopyOnWriteArrayList<T>() : list;
    for (T item : items) {
        list.add(item);
    }
    return list;
}
 
Example 11
Source File: AbstractProtocolManagerFactory.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * This method exists because java templates won't store the type of P at runtime.
 * So it's not possible to write a generic method with having the Class Type.
 * This will serve as a tool for sub classes to filter properly* * *
 *
 * @param type
 * @param listIn
 * @return
 */
protected List<P> internalFilterInterceptors(Class<P> type, List<? extends BaseInterceptor> listIn) {
   if (listIn == null) {
      return Collections.emptyList();
   } else {
      CopyOnWriteArrayList<P> listOut = new CopyOnWriteArrayList<>();
      for (BaseInterceptor<?> in : listIn) {
         if (type.isInstance(in)) {
            listOut.add((P) in);
         }
      }
      return listOut;
   }
}
 
Example 12
Source File: RandomTests.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultithreading2() throws Exception {

    final AtomicInteger cnt = new AtomicInteger(0);
    final CopyOnWriteArrayList<INDArray> list = new CopyOnWriteArrayList<>();

    Thread[] threads = new Thread[10];
    for (int x = 0; x < threads.length; x++) {
        list.add(null);
    }

    for (int x = 0; x < threads.length; x++) {
        threads[x] = new Thread(new Runnable() {
            @Override
            public void run() {
                Random rnd = Nd4j.getRandom();
                rnd.setSeed(119);
                INDArray array = Nd4j.getExecutioner().exec(new UniformDistribution(Nd4j.createUninitialized(25)));

                Nd4j.getExecutioner().commit();

                list.set(cnt.getAndIncrement(), array);
            }
        });
        threads[x].start();
    }

    // we want all threads finished before comparing arrays
    for (int x = 0; x < threads.length; x++)
        threads[x].join();

    for (int x = 0; x < threads.length; x++) {
        assertNotEquals(null, list.get(x));

        if (x > 0) {
            assertEquals(list.get(0), list.get(x));
        }
    }
}
 
Example 13
Source File: CopyOnWriteArrayListTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * lastIndexOf returns the index for the given object
 */
public void testLastIndexOf1() {
    CopyOnWriteArrayList full = populatedArray(3);
    full.add(one);
    full.add(three);
    assertEquals(3, full.lastIndexOf(one));
    assertEquals(-1, full.lastIndexOf(six));
}
 
Example 14
Source File: CopyOnWriteArrayListTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static CopyOnWriteArrayList<Integer> populatedArray(Integer[] elements) {
    CopyOnWriteArrayList<Integer> a = new CopyOnWriteArrayList<>();
    assertTrue(a.isEmpty());
    for (int i = 0; i < elements.length; i++)
        a.add(elements[i]);
    assertFalse(a.isEmpty());
    assertEquals(elements.length, a.size());
    return a;
}
 
Example 15
Source File: CopyOnWriteArrayListTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
static CopyOnWriteArrayList<Integer> populatedArray(int n) {
    CopyOnWriteArrayList<Integer> a = new CopyOnWriteArrayList<Integer>();
    assertTrue(a.isEmpty());
    for (int i = 0; i < n; i++)
        a.add(i);
    assertFalse(a.isEmpty());
    assertEquals(n, a.size());
    return a;
}
 
Example 16
Source File: CopyOnWriteArrayListTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * adding at an index places it in the indicated index
 */
public void testAddIndex() {
    CopyOnWriteArrayList full = populatedArray(3);
    full.add(0, m1);
    assertEquals(4, full.size());
    assertEquals(m1, full.get(0));
    assertEquals(zero, full.get(1));

    full.add(2, m2);
    assertEquals(5, full.size());
    assertEquals(m2, full.get(2));
    assertEquals(two, full.get(4));
}
 
Example 17
Source File: VoltronProxyInvocationHandler.java    From terracotta-platform with Apache License 2.0 4 votes vote down vote up
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {

  if (close.equals(method)) {
    handler.shutdown();
    entityClientEndpoint.close();
    return null;

  } else if (registerMessageListener.equals(method)) {
    final Class<?> eventType = (Class<?>) args[0];
    final MessageListener<?> arg = (MessageListener<?>) args[1];
    final CopyOnWriteArrayList<MessageListener<?>> messageListeners = listeners.get(eventType);
    if (messageListeners == null) {
      throw new IllegalArgumentException("Event type '" + eventType + "' isn't supported");
    }
    messageListeners.add(arg);
    return null;

  } else if (setEndpointListener.equals(method)) {
    this.endpointListener = (EndpointListener) args[0];
    return null;
  }

  final MethodDescriptor methodDescriptor = MethodDescriptor.of(method);

  final InvocationBuilder<ProxyEntityMessage, ProxyEntityResponse> builder = entityClientEndpoint.beginInvoke()
      .message(new ProxyEntityMessage(methodDescriptor, args, MessageType.MESSAGE)).withExecutor(handler);

  if (methodDescriptor.isAsync()) {
    switch (methodDescriptor.getAck()) {
      case NONE:
        break;
      case RECEIVED:
        builder.ackReceived();
        break;
      default:
        throw new IllegalStateException(methodDescriptor.getAck().name());
    }
    return new ProxiedInvokeFuture<>(builder.invoke());

  } else {
    return getResponse(builder.invoke().get());
  }
}
 
Example 18
Source File: DingTalkRobotConfig.java    From dingtalk-plugin with MIT License 4 votes vote down vote up
/**
 * 测试配置信息
 *
 * @param id                      id
 * @param name                    名称
 * @param webhook                 webhook
 * @param securityPolicyConfigStr 安全策略
 * @return 机器人配置是否正确
 */
public FormValidation doTest(
    @QueryParameter("id") String id,
    @QueryParameter("name") String name,
    @QueryParameter("webhook") String webhook,
    @QueryParameter("securityPolicyConfigs") String securityPolicyConfigStr
) {
  CopyOnWriteArrayList<DingTalkSecurityPolicyConfig> securityPolicyConfigs = new CopyOnWriteArrayList<>();
  JSONArray array = (JSONArray) JSONSerializer.toJSON(securityPolicyConfigStr);
  for (Object item : array) {
    JSONObject json = (JSONObject) item;
    securityPolicyConfigs.add(
        new DingTalkSecurityPolicyConfig(
            (Boolean) json.get("checked"),
            (String) json.get("type"),
            (String) json.get("value"),
            ""
        )
    );
  }
  DingTalkRobotConfig robotConfig = new DingTalkRobotConfig(
      id,
      name,
      webhook,
      securityPolicyConfigs
  );
  DingTalkSender sender = new DingTalkSender(robotConfig);
  String rootUrl = Jenkins.get().getRootUrl();
  User user = User.current();
  if (user == null) {
    user = User.getUnknown();
  }
  String text = BuildJobModel
      .builder()
      .projectName("欢迎使用钉钉机器人插件~")
      .projectUrl(rootUrl)
      .jobName("系统配置")
      .jobUrl(rootUrl + "/configure")
      .statusType(BuildStatusEnum.SUCCESS)
      .duration("-")
      .executorName(user.getDisplayName())
      .executorMobile(user.getDescription())
      .build()
      .toMarkdown();
  MessageModel msg = MessageModel
      .builder()
      .type(MsgTypeEnum.MARKDOWN)
      .title("钉钉机器人测试成功")
      .text(text)
      .atAll(true)
      .build();
  String message = sender.sendMarkdown(msg);
  if (message == null) {
    return FormValidation
        .respond(
            Kind.OK,
            "<img src='"
                + rootUrl
                + "/images/16x16/accept.png'>"
                + "<span style='padding-left:4px;color:#52c41a;font-weight:bold;'>测试成功</span>"
        );
  }
  return FormValidation.error(message);
}
 
Example 19
Source File: DownloadQueue.java    From NClientV2 with Apache License 2.0 4 votes vote down vote up
public static CopyOnWriteArrayList<GalleryDownloaderV2> getDownloaders() {
    CopyOnWriteArrayList<GalleryDownloaderV2> downloaders = new CopyOnWriteArrayList<>();
    for (GalleryDownloaderManager manager : downloadQueue)
        downloaders.add(manager.downloader());
    return downloaders;
}
 
Example 20
Source File: X8sPanelRecycleAdapter.java    From FimiX8-RE with MIT License 4 votes vote down vote up
public void addItemReally(T mediaModel) {
    changeMediaModelState(mediaModel);
    int inserterPosition = 0;
    if (mediaModel != null) {
        int modelNoHeadListPosition = 0;
        Iterator it = this.modelNoHeadList.iterator();
        while (it.hasNext()) {
            if (mediaModel.getFormatDate().compareTo(((MediaModel) it.next()).getFormatDate()) > 0) {
                break;
            }
            modelNoHeadListPosition++;
        }
        this.modelNoHeadList.add(modelNoHeadListPosition, mediaModel);
        statisticalFileCount(mediaModel, true);
        String currentFormatData = mediaModel.getFormatDate().split(" ")[0];
        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();
            }
            if (this.modelList.size() == 0) {
                MediaModel headviewModel = new MediaModel();
                headviewModel.setHeadView(true);
                this.modelList.add(0, headviewModel);
                inserterPosition++;
                if (this.isCamera) {
                    DataManager.obtain().setX9CameralLoad(true);
                } else {
                    DataManager.obtain().setLocalLoad(true);
                }
            } else {
                inserterPosition++;
            }
            MediaModel 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;
    message.obj = mediaModel;
    this.mainHandler.sendMessage(message);
}