Example usage for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList

List of usage examples for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList

Introduction

In this page you can find the example usage for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList.

Prototype

public CopyOnWriteArrayList() 

Source Link

Document

Creates an empty list.

Usage

From source file:org.kie.server.services.impl.KieServerImpl.java

protected List<Message> getMessagesForContainer(String containerId) {
    List<Message> messages = containerMessages.get(containerId);

    if (messages == null) {
        messages = new CopyOnWriteArrayList<Message>();
        containerMessages.put(containerId, messages);
    }/*from w w  w. j  a  v a2  s  .co  m*/

    return messages;
}

From source file:org.elasticsearch.test.ElasticsearchIntegrationTest.java

/**
 * Indexes the given {@link IndexRequestBuilder} instances randomly. It shuffles the given builders and either
 * indexes they in a blocking or async fashion. This is very useful to catch problems that relate to internal document
 * ids or index segment creations. Some features might have bug when a given document is the first or the last in a
 * segment or if only one document is in a segment etc. This method prevents issues like this by randomizing the index
 * layout.//from   w w w  .j av  a  2 s  . c  o m
 *
 * @param forceRefresh   if <tt>true</tt> all involved indices are refreshed once the documents are indexed.
 * @param dummyDocuments if <tt>true</tt> some empty dummy documents may be randomly inserted into the document list and deleted once
 *                       all documents are indexed. This is useful to produce deleted documents on the server side.
 * @param maybeFlush     if <tt>true</tt> this method may randomly execute full flushes after index operations.
 * @param builders       the documents to index.
 */
public void indexRandom(boolean forceRefresh, boolean dummyDocuments, boolean maybeFlush,
        List<IndexRequestBuilder> builders) throws InterruptedException, ExecutionException {

    Random random = getRandom();
    Set<String> indicesSet = new HashSet<>();
    for (IndexRequestBuilder builder : builders) {
        indicesSet.add(builder.request().index());
    }
    Set<Tuple<String, String>> bogusIds = new HashSet<>();
    if (random.nextBoolean() && !builders.isEmpty() && dummyDocuments) {
        builders = new ArrayList<>(builders);
        final String[] indices = indicesSet.toArray(new String[indicesSet.size()]);
        // inject some bogus docs
        final int numBogusDocs = scaledRandomIntBetween(1, builders.size() * 2);
        final int unicodeLen = between(1, 10);
        for (int i = 0; i < numBogusDocs; i++) {
            String id = randomRealisticUnicodeOfLength(unicodeLen)
                    + Integer.toString(dummmyDocIdGenerator.incrementAndGet());
            String index = RandomPicks.randomFrom(random, indices);
            bogusIds.add(new Tuple<>(index, id));
            builders.add(client().prepareIndex(index, RANDOM_BOGUS_TYPE, id).setSource("{}"));
        }
    }
    final String[] indices = indicesSet.toArray(new String[indicesSet.size()]);
    Collections.shuffle(builders, random);
    final CopyOnWriteArrayList<Tuple<IndexRequestBuilder, Throwable>> errors = new CopyOnWriteArrayList<>();
    List<CountDownLatch> inFlightAsyncOperations = new ArrayList<>();
    // If you are indexing just a few documents then frequently do it one at a time.  If many then frequently in bulk.
    if (builders.size() < FREQUENT_BULK_THRESHOLD ? frequently()
            : builders.size() < ALWAYS_BULK_THRESHOLD ? rarely() : false) {
        if (frequently()) {
            logger.info("Index [{}] docs async: [{}] bulk: [{}]", builders.size(), true, false);
            for (IndexRequestBuilder indexRequestBuilder : builders) {
                indexRequestBuilder
                        .execute(new PayloadLatchedActionListener<IndexResponse, IndexRequestBuilder>(
                                indexRequestBuilder, newLatch(inFlightAsyncOperations), errors));
                postIndexAsyncActions(indices, inFlightAsyncOperations, maybeFlush);
            }
        } else {
            logger.info("Index [{}] docs async: [{}] bulk: [{}]", builders.size(), false, false);
            for (IndexRequestBuilder indexRequestBuilder : builders) {
                indexRequestBuilder.execute().actionGet();
                postIndexAsyncActions(indices, inFlightAsyncOperations, maybeFlush);
            }
        }
    } else {
        List<List<IndexRequestBuilder>> partition = Lists.partition(builders,
                Math.min(MAX_BULK_INDEX_REQUEST_SIZE, Math.max(1, (int) (builders.size() * randomDouble()))));
        logger.info("Index [{}] docs async: [{}] bulk: [{}] partitions [{}]", builders.size(), false, true,
                partition.size());
        for (List<IndexRequestBuilder> segmented : partition) {
            BulkRequestBuilder bulkBuilder = client().prepareBulk();
            for (IndexRequestBuilder indexRequestBuilder : segmented) {
                bulkBuilder.add(indexRequestBuilder);
            }
            BulkResponse actionGet = bulkBuilder.execute().actionGet();
            assertThat(actionGet.hasFailures() ? actionGet.buildFailureMessage() : "", actionGet.hasFailures(),
                    equalTo(false));
        }
    }
    for (CountDownLatch operation : inFlightAsyncOperations) {
        operation.await();
    }
    final List<Throwable> actualErrors = new ArrayList<>();
    for (Tuple<IndexRequestBuilder, Throwable> tuple : errors) {
        if (ExceptionsHelper.unwrapCause(tuple.v2()) instanceof EsRejectedExecutionException) {
            tuple.v1().execute().actionGet(); // re-index if rejected
        } else {
            actualErrors.add(tuple.v2());
        }
    }
    assertThat(actualErrors, emptyIterable());
    if (!bogusIds.isEmpty()) {
        // delete the bogus types again - it might trigger merges or at least holes in the segments and enforces deleted docs!
        for (Tuple<String, String> doc : bogusIds) {
            // see https://github.com/elasticsearch/elasticsearch/issues/8706
            final DeleteResponse deleteResponse = client().prepareDelete(doc.v1(), RANDOM_BOGUS_TYPE, doc.v2())
                    .get();
            if (deleteResponse.isFound() == false) {
                logger.warn("failed to delete a dummy doc [{}][{}]", doc.v1(), doc.v2());
            }
        }
    }
    if (forceRefresh) {
        assertNoFailures(client().admin().indices().prepareRefresh(indices)
                .setIndicesOptions(IndicesOptions.lenientExpandOpen()).execute().get());
    }
}

From source file:org.apache.druid.indexing.kafka.supervisor.KafkaSupervisor.java

private void addDiscoveredTaskToPendingCompletionTaskGroups(int groupId, String taskId,
        Map<Integer, Long> startingPartitions) {
    final CopyOnWriteArrayList<TaskGroup> taskGroupList = pendingCompletionTaskGroups.computeIfAbsent(groupId,
            k -> new CopyOnWriteArrayList<>());
    for (TaskGroup taskGroup : taskGroupList) {
        if (taskGroup.partitionOffsets.equals(startingPartitions)) {
            if (taskGroup.tasks.putIfAbsent(taskId, new TaskData()) == null) {
                log.info("Added discovered task [%s] to existing pending task group [%s]", taskId, groupId);
            }/*from  www  . ja va  2  s  .c  om*/
            return;
        }
    }

    log.info("Creating new pending completion task group [%s] for discovered task [%s]", groupId, taskId);

    // reading the minimumMessageTime & maximumMessageTime from the publishing task and setting it here is not necessary as this task cannot
    // change to a state where it will read any more events
    TaskGroup newTaskGroup = new TaskGroup(groupId, ImmutableMap.copyOf(startingPartitions), Optional.absent(),
            Optional.absent());

    newTaskGroup.tasks.put(taskId, new TaskData());
    newTaskGroup.completionTimeout = DateTimes.nowUtc().plus(ioConfig.getCompletionTimeout());

    taskGroupList.add(newTaskGroup);
}

From source file:org.openspotlight.storage.test.AbstractStorageSessionTest.java

@Test
public void shouldInstantiateOneSessionPerThread() throws Exception {
    final StorageSession session1 = autoFlushInjector.getInstance(StorageSession.class);
    final StorageSession session2 = autoFlushInjector.getInstance(StorageSession.class);
    assertThat(session1, is(session2));// w  w  w.  ja v a2 s  . c  om

    final List<StorageSession> sessions = new CopyOnWriteArrayList<StorageSession>();
    final CountDownLatch latch = new CountDownLatch(1);

    new Thread() {
        @Override
        public void run() {
            try {
                sessions.add(autoFlushInjector.getInstance(StorageSession.class));
            } finally {
                latch.countDown();
            }
        }
    }.start();
    latch.await(5, TimeUnit.SECONDS);
    assertThat(sessions.size(), is(1));
    assertThat(session1, is(not(sessions.get(0))));
}

From source file:org.apache.druid.indexing.kafka.supervisor.KafkaSupervisor.java

private void checkTaskDuration() throws InterruptedException, ExecutionException, TimeoutException {
    final List<ListenableFuture<Map<Integer, Long>>> futures = Lists.newArrayList();
    final List<Integer> futureGroupIds = Lists.newArrayList();

    for (Entry<Integer, TaskGroup> entry : taskGroups.entrySet()) {
        Integer groupId = entry.getKey();
        TaskGroup group = entry.getValue();

        // find the longest running task from this group
        DateTime earliestTaskStart = DateTimes.nowUtc();
        for (TaskData taskData : group.tasks.values()) {
            // startTime can be null if kafkaSupervisor is stopped gracefully before processing any runNotice
            if (taskData.startTime != null && earliestTaskStart.isAfter(taskData.startTime)) {
                earliestTaskStart = taskData.startTime;
            }//from ww w. j a va 2  s  . c  o  m
        }

        // if this task has run longer than the configured duration, signal all tasks in the group to persist
        if (earliestTaskStart.plus(ioConfig.getTaskDuration()).isBeforeNow()) {
            log.info("Task group [%d] has run for [%s]", groupId, ioConfig.getTaskDuration());
            futureGroupIds.add(groupId);
            futures.add(checkpointTaskGroup(group, true));
        }
    }

    List<Map<Integer, Long>> results = Futures.successfulAsList(futures).get(futureTimeoutInSeconds,
            TimeUnit.SECONDS);
    for (int j = 0; j < results.size(); j++) {
        Integer groupId = futureGroupIds.get(j);
        TaskGroup group = taskGroups.get(groupId);
        Map<Integer, Long> endOffsets = results.get(j);

        if (endOffsets != null) {
            // set a timeout and put this group in pendingCompletionTaskGroups so that it can be monitored for completion
            group.completionTimeout = DateTimes.nowUtc().plus(ioConfig.getCompletionTimeout());
            pendingCompletionTaskGroups.computeIfAbsent(groupId, k -> new CopyOnWriteArrayList<>()).add(group);

            // set endOffsets as the next startOffsets
            for (Entry<Integer, Long> entry : endOffsets.entrySet()) {
                partitionGroups.get(groupId).put(entry.getKey(), entry.getValue());
            }
        } else {
            log.warn("All tasks in group [%s] failed to transition to publishing state, killing tasks [%s]",
                    groupId, group.taskIds());
            for (String id : group.taskIds()) {
                killTask(id);
            }
            // clear partitionGroups, so that latest offsets from db is used as start offsets not the stale ones
            // if tasks did some successful incremental handoffs
            partitionGroups.get(groupId).replaceAll((partition, offset) -> NOT_SET);
        }

        // remove this task group from the list of current task groups now that it has been handled
        taskGroups.remove(groupId);
    }
}

From source file:com.l2jfree.gameserver.model.entity.events.CTF.java

public static boolean addPlayerOk(String teamName, L2Player eventPlayer) {
    if (GlobalRestrictions.isRestricted(eventPlayer, CTFRestriction.class)) {
        // TODO: msg
        return false;
    }/*from  w w w  .  j av a 2  s.c  o m*/

    try {
        if (checkShufflePlayers(eventPlayer) || eventPlayer.isInEvent(CTFPlayerInfo.class)) {
            eventPlayer.sendMessage("You are already participating in the event!");
            return false;
        }

        for (L2Player player : _players) {
            if (player.getObjectId() == eventPlayer.getObjectId()) {
                eventPlayer.sendMessage("You are already participating in the event!");
                return false;
            } else if (player.getName() == eventPlayer.getName()) {
                eventPlayer.sendMessage("You are already participating in the event!");
                return false;
            }
        }
        if (_players.contains(eventPlayer)) {
            eventPlayer.sendMessage("You are already participating in the event!");
            return false;
        }
        if (TvT._savePlayers.contains(eventPlayer.getName())) {
            eventPlayer.sendMessage("You are already participating in another event!");
            return false;
        }
    } catch (Exception e) {
        _log.warn("CTF Siege Engine exception: ", e);
    }

    if (Config.CTF_EVEN_TEAMS.equals("NO"))
        return true;
    else if (Config.CTF_EVEN_TEAMS.equals("BALANCE")) {
        boolean allTeamsEqual = true;
        int countBefore = -1;

        for (int playersCount : _teamPlayersCount) {
            if (countBefore == -1)
                countBefore = playersCount;

            if (countBefore != playersCount) {
                allTeamsEqual = false;
                break;
            }

            countBefore = playersCount;
        }

        if (allTeamsEqual)
            return true;

        countBefore = Integer.MAX_VALUE;

        for (int teamPlayerCount : _teamPlayersCount) {
            if (teamPlayerCount < countBefore)
                countBefore = teamPlayerCount;
        }

        CopyOnWriteArrayList<String> joinableTeams = new CopyOnWriteArrayList<String>();

        for (String team : _teams) {
            if (teamPlayersCount(team) == countBefore)
                joinableTeams.add(team);
        }

        if (joinableTeams.contains(teamName))
            return true;
    } else if (Config.CTF_EVEN_TEAMS.equals("SHUFFLE"))
        return true;

    eventPlayer.sendMessage("Too many players in team \"" + teamName + "\"");
    return false;
}

From source file:com.l2jfree.gameserver.model.entity.events.CTF.java

public static void cleanCTF() {
    _log.info("CTF : Cleaning players.");
    for (L2Player player : _players) {
        if (player != null) {
            final CTFPlayerInfo info = player.as(CTFPlayerInfo.class);

            if (info._haveFlagCTF)
                removeFlagFromPlayer(player);
            else/*from   ww  w . j av  a2s .c  o m*/
                player.getInventory().destroyItemByItemId("", CTF._FLAG_IN_HAND_ITEM_ID, 1, player, null);
            info._haveFlagCTF = false;
            removePlayer(player);
        }
    }
    if (_playersShuffle != null && !_playersShuffle.isEmpty()) {
        for (L2Player player : _playersShuffle) {
            if (player != null)
                player.setPlayerInfo(null);
        }
    }
    _log.info("CTF : Cleaning teams and flags.");
    for (String team : _teams) {
        int index = _teams.indexOf(team);
        _teamPointsCount.set(index, 0);
        _flagSpawns.set(index, null);
        _flagsTaken.set(index, false);
        _teamPlayersCount.set(index, 0);
        _teamPointsCount.set(index, 0);
    }
    _topScore = 0;
    _topTeam = "";
    _players.clear();
    _playersShuffle.clear();
    _savePlayers = new CopyOnWriteArrayList<String>();
    _savePlayerTeams = new CopyOnWriteArrayList<String>();
    _teamPointsCount = new CopyOnWriteArrayList<Integer>();
    _flagSpawns = new CopyOnWriteArrayList<L2Spawn>();
    _flagsTaken = new CopyOnWriteArrayList<Boolean>();
    _teamPlayersCount = new CopyOnWriteArrayList<Integer>();
    _log.info("Cleaning CTF done.");
    _log.info("Loading new data from MySql");
    loadData();
}

From source file:org.restcomm.connect.telephony.CallManager.java

private void outboundToClient(final CreateCall request, final ActorRef sender) throws ServletParseException {
    SipURI outboundIntf = null;//w  ww  .  ja v  a 2  s  .c o m
    SipURI from = null;
    SipURI to = null;
    boolean webRTC = false;
    boolean isLBPresent = false;

    final RegistrationsDao registrationsDao = storage.getRegistrationsDao();
    final String client = request.to().replaceFirst("client:", "");

    //1, If this is a WebRTC client check if the instance is the current instance
    //2. Check if the client has more than one registrations

    List<Registration> registrationToDial = new CopyOnWriteArrayList<Registration>();

    List<Registration> registrations = registrationsDao.getRegistrations(client);
    if (registrations != null && registrations.size() > 0) {
        if (logger.isInfoEnabled()) {
            logger.info("Preparing call for client: " + client + ". There are " + registrations.size()
                    + " registrations at the database for this client");
        }
        for (Registration registration : registrations) {
            if (registration.isWebRTC()) {
                if (registration.isLBPresent()) {
                    if (logger.isInfoEnabled())
                        logger.info("WebRTC registration behind LB. Will add WebRTC registration: "
                                + registration.getLocation() + " to the list to be dialed for client: "
                                + client);
                    registrationToDial.add(registration);
                } else {
                    //If this is a WebRTC client registration, check that the InstanceId of the registration is for the current Restcomm instance
                    if ((registration.getInstanceId() != null && !registration.getInstanceId()
                            .equals(RestcommConfiguration.getInstance().getMain().getInstanceId()))) {
                        logger.warning("Cannot create call for user agent: " + registration.getLocation()
                                + " since this is a webrtc client registered in another Restcomm instance.");
                    } else {
                        if (logger.isInfoEnabled())
                            logger.info("Will add WebRTC registration: " + registration.getLocation()
                                    + " to the list to be dialed for client: " + client);
                        registrationToDial.add(registration);
                    }
                }
            } else {
                if (logger.isInfoEnabled())
                    logger.info("Will add registration: " + registration.getLocation()
                            + " to the list to be dialed for client: " + client);
                registrationToDial.add(registration);
            }
        }
    } else {
        String errMsg = "The SIP Client " + request.to() + " is not registered or does not exist";
        logger.warning(errMsg);
        sendNotification(errMsg, 11008, "error", true);
        sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), this.createCallRequest),
                self());
        return;
    }

    if (registrationToDial.size() > 0) {
        if (logger.isInfoEnabled()) {
            if (registrationToDial.size() > 1) {
                logger.info(
                        "Preparing call for client: " + client + ", after WebRTC check, Restcomm have to dial :"
                                + registrationToDial.size() + " registrations");
            }
        }
        List<ActorRef> calls = new CopyOnWriteArrayList<>();
        for (Registration registration : registrationToDial) {
            if (logger.isInfoEnabled())
                logger.info("Will proceed to create call for client: " + registration.getLocation()
                        + " registration instanceId: " + registration.getInstanceId() + " own InstanceId: "
                        + RestcommConfiguration.getInstance().getMain().getInstanceId());
            String transport;
            if (registration.getLocation().contains("transport")) {
                transport = registration.getLocation().split(";")[1].replace("transport=", "");
                outboundIntf = outboundInterface(transport);
            } else {
                transport = "udp";
                outboundIntf = outboundInterface(transport);
            }
            if (outboundIntf == null) {
                String errMsg = "The outbound interface for transport: " + transport
                        + " is NULL, something is wrong with container, cannot proceed to call client "
                        + request.to();
                logger.error(errMsg);
                sendNotification(errMsg, 11008, "error", true);
                sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg),
                        this.createCallRequest), self());
                return;
            }
            if (request.from() != null && request.from().contains("@")) {
                // https://github.com/Mobicents/RestComm/issues/150 if it contains @ it means this is a sip uri and we allow
                // to use it directly
                from = (SipURI) sipFactory.createURI(request.from());
            } else if (request.from() != null) {
                if (outboundIntf != null) {
                    from = sipFactory.createSipURI(request.from(),
                            mediaExternalIp + ":" + outboundIntf.getPort());
                } else {
                    logger.error(
                            "Outbound interface is null, cannot create From header to be used to Dial client: "
                                    + client);
                }
            } else {
                from = outboundIntf;
            }
            final String location = registration.getLocation();
            to = (SipURI) sipFactory.createURI(location);
            webRTC = registration.isWebRTC();
            if (from == null || to == null) {
                //In case From or To are null we have to cancel outbound call and hnagup initial call if needed
                final String errMsg = "From and/or To are null, we cannot proceed to the outbound call to: "
                        + request.to();
                logger.warning(errMsg);
                sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg),
                        this.createCallRequest), self());
            } else {
                calls.add(createOutbound(request, from, to, webRTC));
            }
        }
        if (calls.size() > 0) {
            sender.tell(new CallManagerResponse<List<ActorRef>>(calls), self());
        }
    } else {
        String errMsg = "The SIP Client " + request.to() + " is not registered or does not exist";
        logger.warning(errMsg);
        sendNotification(errMsg, 11008, "error", true);
        sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), this.createCallRequest),
                self());
    }
}

From source file:org.apache.druid.indexing.kafka.supervisor.KafkaSupervisor.java

@VisibleForTesting
void moveTaskGroupToPendingCompletion(int taskGroupId) {
    final TaskGroup taskGroup = taskGroups.remove(taskGroupId);
    if (taskGroup != null) {
        pendingCompletionTaskGroups.computeIfAbsent(taskGroupId, k -> new CopyOnWriteArrayList<>())
                .add(taskGroup);/* w  ww.j a  va 2 s  .c  om*/
    }
}