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:com.connectsdk.device.ConnectableDevice.java

/**
 * Clears the array of listeners and adds the provided `listener` to the array. If `listener` is null, the array will be empty.
 * //w  ww  .ja va  2 s.co m
 * This method is deprecated. Since version 1.2.1, use
 * `ConnectableDevice#addListener(ConnectableDeviceListener listener)` instead
 * 
 * @param listener ConnectableDeviceListener to listen to device events (connect, disconnect, ready, etc)
 */
@Deprecated
public void setListener(ConnectableDeviceListener listener) {
    listeners = new CopyOnWriteArrayList<ConnectableDeviceListener>();

    if (listener != null)
        listeners.add(listener);
}

From source file:com.photon.phresco.framework.impl.ApplicationManagerImpl.java

@Override
public void deleteBuildInfos(String rootModulePath, int[] buildNumbers, String subModule)
        throws PhrescoException {
    S_LOGGER.debug(/*from www  .j av a  2  s  . com*/
            "Entering Method ApplicationManagerImpl.deleteBuildInfos(ProjectInfo project, int[] buildNumbers)");

    String buildInfoFile = getBuildInfoFilePath(rootModulePath, subModule);
    List<BuildInfo> totalBuildInfos = getBuildInfos(new File(buildInfoFile));
    List<BuildInfo> buildInfos = new CopyOnWriteArrayList<BuildInfo>();
    BuildInfo buildInfo;
    for (int i = 0; i < buildNumbers.length; i++) {
        buildInfo = getBuildInfo(buildNumbers[i], buildInfoFile);
        buildInfos.add(buildInfo);
    }

    deleteBuildArchive(rootModulePath, buildInfos, subModule);

    for (BuildInfo selectedInfo : buildInfos) {
        Iterator<BuildInfo> iterator = totalBuildInfos.iterator();
        while (iterator.hasNext()) {
            BuildInfo bi = iterator.next();
            if (bi.getBuildNo() == selectedInfo.getBuildNo()) {
                iterator.remove();
                break;
            }
        }
    }

    try {
        writeBuildInfo(totalBuildInfos, new File(buildInfoFile));
    } catch (IOException e) {
        throw new PhrescoException(e);
    }
}

From source file:com.all.messengine.impl.StubMessEngine.java

@SuppressWarnings("unchecked")
@Override/*from  w w  w  . j a v a2s.com*/
public void addMessageListener(String type, MessageListener<? extends Message<?>> listener) {
    List<MessageListener<Message<?>>> list = listeners.get(type);
    if (list == null) {
        list = new CopyOnWriteArrayList<MessageListener<Message<?>>>();
        listeners.put(type, list);
    }
    list.add((MessageListener<Message<?>>) listener);
}

From source file:org.jiemamy.utils.collection.CollectionsUtil.java

/**
 * {@link CopyOnWriteArrayList}?????/*  ww w. jav  a 2s .  c om*/
 * 
 * @param <E> {@link CopyOnWriteArrayList}??
 * @return {@link CopyOnWriteArrayList}???
 * @see CopyOnWriteArrayList#CopyOnWriteArrayList()
 */
public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
    return new CopyOnWriteArrayList<E>();
}

From source file:com.shipdream.lib.android.mvc.view.MvcFragment.java

/**
 * Register a callback after {@link #onViewReady(View, Bundle, Reason)} is called. This is useful when an action that
 * can't be executed after the fragment is instantiated but before the fragment has gone through
 * life cycles and gets created and ready to use. If this is one time action, use
 * {@link #unregisterOnViewReadyListener(Runnable)} (Runnable)}  unregister itself in the given onCreateViewAction.
 *
 * @param onCreateViewAction The action to register
 *//*from   w  w w. ja  va  2 s  .c o  m*/
public void registerOnViewReadyListener(Runnable onCreateViewAction) {
    if (onViewReadyListeners == null) {
        onViewReadyListeners = new CopyOnWriteArrayList<>();
    }
    onViewReadyListeners.add(onCreateViewAction);
}

From source file:org.opendaylight.controller.sal.implementation.internal.DataPacketService.java

void setListenDataPacket(Map props, IListenDataPacket s) {
    if (this.listenDataPacket == null || this.indexDataPacket == null) {
        logger.error("data structure to store data is NULL");
        return;/*from  ww w  .  j a  v a  2 s.  c  om*/
    }
    logger.trace("Received setListenDataPacket request");
    for (Object e : props.entrySet()) {
        Map.Entry entry = (Map.Entry) e;
        logger.trace("Prop key:({}) value:({})", entry.getKey(), entry.getValue());
    }

    String listenerName = null;
    String listenerDependency = null;
    Match filter = null;
    Object value;
    // Read the listenerName
    value = props.get("salListenerName");
    if (value instanceof String) {
        listenerName = (String) value;
    }

    if (listenerName == null) {
        logger.error("Trying to set a listener without a Name");
        return;
    }

    //Read the dependency
    value = props.get("salListenerDependency");
    if (value instanceof String) {
        listenerDependency = (String) value;
    }

    //Read match filter if any
    value = props.get("salListenerFilter");
    if (value instanceof Match) {
        filter = (Match) value;
    }

    DataPacketListener l = new DataPacketListener(listenerName, s, listenerDependency, filter);

    DataPacketListener lDependency = new DataPacketListener(listenerDependency, null, null, null);

    // Now let see if there is any dependency
    if (listenerDependency == null) {
        logger.debug("listener without any dependency");
        if (this.indexDataPacket.contains(l)) {
            logger.error("trying to add an existing element");
        } else {
            logger.debug("adding listener: {}", listenerName);
            CopyOnWriteArrayList<DataPacketListener> serialListeners = new CopyOnWriteArrayList<DataPacketListener>();
            serialListeners.add(l);
            this.listenDataPacket.add(serialListeners);
            this.indexDataPacket.add(l);
        }
    } else {
        logger.debug("listener with dependency");
        // Now search for the dependency and put things in order
        if (this.indexDataPacket.contains(l)) {
            logger.error("trying to add an existing element");
        } else {
            logger.debug("adding listener: {}", listenerName);
            // Lets find the set with the dependency in it, if we
            // find it lets just add our dependency at the end of
            // the list.
            for (List<DataPacketListener> serialListeners : this.listenDataPacket) {
                int i = 0;
                boolean done = false;
                if (serialListeners.contains(lDependency)) {
                    serialListeners.add(l);
                    done = true;
                }
                // If we did fine the element, lets break early
                if (done) {
                    break;
                }
            }

            this.indexDataPacket.add(l);
        }
    }
}

From source file:org.apache.sshd.PortForwardingLoadTest.java

@Test
public void testForwardingOnLoad() throws Exception {
    //        final String path = "/history/recent/troubles/";
    //        final String host = "www.bbc.co.uk";
    //        final String path = "";
    //        final String host = "www.bahn.de";
    final String path = "";
    final String host = "localhost";
    final int nbThread = 2;
    final int nbDownloads = 2;
    final int nbLoops = 2;

    final int port = getFreePort();
    StringBuilder resp = new StringBuilder();
    resp.append("<html><body>\n");
    for (int i = 0; i < 1000; i++) {
        resp.append("0123456789\n");
    }/*ww  w. j a  v a  2  s  . c o  m*/
    resp.append("</body></html>\n");
    final StringBuilder sb = new StringBuilder();
    sb.append("HTTP/1.1 200 OK").append('\n');
    sb.append("Content-Type: text/HTML").append('\n');
    sb.append("Content-Length: ").append(resp.length()).append('\n');
    sb.append('\n');
    sb.append(resp);
    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            session.write(IoBuffer.wrap(sb.toString().getBytes()));
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(port));

    Session session = createSession();

    final int forwardedPort1 = getFreePort();
    final int forwardedPort2 = getFreePort();
    System.err.println("URL: http://localhost:" + forwardedPort2);

    session.setPortForwardingL(forwardedPort1, host, port);
    session.setPortForwardingR(forwardedPort2, "localhost", forwardedPort1);

    final CountDownLatch latch = new CountDownLatch(nbThread * nbDownloads * nbLoops);

    final Thread[] threads = new Thread[nbThread];
    final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>();
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread() {
            public void run() {
                for (int j = 0; j < nbLoops; j++) {
                    final MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
                    final HttpClient client = new HttpClient(mgr);
                    client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100);
                    client.getHttpConnectionManager().getParams().setMaxTotalConnections(1000);
                    for (int i = 0; i < nbDownloads; i++) {
                        try {
                            checkHtmlPage(client, new URL("http://localhost:" + forwardedPort2 + path));
                        } catch (Throwable e) {
                            errors.add(e);
                        } finally {
                            latch.countDown();
                            System.err.println("Remaining: " + latch.getCount());
                        }
                    }
                    mgr.shutdown();
                }
            }
        };
    }
    for (int i = 0; i < threads.length; i++) {
        threads[i].start();
    }
    latch.await();
    for (Throwable t : errors) {
        t.printStackTrace();
    }
    assertEquals(0, errors.size());
}

From source file:com.comcast.video.dawg.controller.park.ParkController.java

/**
 * Method add the new search condition to the advance search list present in the session. Before adding to the list
 * it removes any duplicate entry present in the list.
 *
 * @param condition//from  ww  w. ja v a2 s  .c  o  m
 *            advance search condition carried out by user.
 * @param session
 *            User session object where user previously executed search conditions are present.
 */
private void validateAndUpdateSessionSearchConditions(Condition condition, HttpSession session) {
    /** Add the new advanced search condition to previously executed search list. */
    List<Condition> searchConditions = (List<Condition>) session
            .getAttribute(SEARCH_CONDITIONS_SESSION_ATTRIBUTE_NAME);
    if (null != searchConditions) {
        // If the user carried out a similar advance search earlier, it need to be removed from the previous
        // stored list.
        searchConditions.remove(condition);
    } else {
        searchConditions = new CopyOnWriteArrayList<Condition>();
    }
    searchConditions.add(condition);
    session.setAttribute(SEARCH_CONDITIONS_SESSION_ATTRIBUTE_NAME, searchConditions);
}

From source file:org.apache.bookkeeper.bookie.EntryLogManagerForEntryLogPerLedger.java

EntryLogManagerForEntryLogPerLedger(ServerConfiguration conf, LedgerDirsManager ledgerDirsManager,
        EntryLoggerAllocator entryLoggerAllocator, List<EntryLogger.EntryLogListener> listeners,
        EntryLogger.RecentEntryLogsStatus recentlyCreatedEntryLogsStatus, StatsLogger statsLogger)
        throws IOException {
    super(conf, ledgerDirsManager, entryLoggerAllocator, listeners);
    this.recentlyCreatedEntryLogsStatus = recentlyCreatedEntryLogsStatus;
    this.rotatedLogChannels = new CopyOnWriteArrayList<BufferedLogChannel>();
    this.replicaOfCurrentLogChannels = new ConcurrentLongHashMap<BufferedLogChannelWithDirInfo>();
    this.entrylogMapAccessExpiryTimeInSeconds = conf.getEntrylogMapAccessExpiryTimeInSeconds();
    this.maximumNumberOfActiveEntryLogs = conf.getMaximumNumberOfActiveEntryLogs();
    this.entryLogPerLedgerCounterLimitsMultFactor = conf.getEntryLogPerLedgerCounterLimitsMultFactor();

    ledgerDirsManager.addLedgerDirsListener(getLedgerDirsListener());
    this.lockArrayPool = new AtomicReferenceArray<Lock>(maximumNumberOfActiveEntryLogs * 2);
    this.entryLogAndLockTupleCacheLoader = new CacheLoader<Long, EntryLogAndLockTuple>() {
        @Override/* w  w  w.j  a  va 2s .co m*/
        public EntryLogAndLockTuple load(Long key) throws Exception {
            return new EntryLogAndLockTuple(key);
        }
    };
    /*
     * Currently we are relying on access time based eviction policy for
     * removal of EntryLogAndLockTuple, so if the EntryLogAndLockTuple of
     * the ledger is not accessed in
     * entrylogMapAccessExpiryTimeInSeconds period, it will be removed
     * from the cache.
     *
     * We are going to introduce explicit advisory writeClose call, with
     * that explicit call EntryLogAndLockTuple of the ledger will be
     * removed from the cache. But still timebased eviciton policy is
     * needed because it is not guaranteed that Bookie/EntryLogger would
     * receive successfully write close call in all the cases.
     */
    ledgerIdEntryLogMap = CacheBuilder.newBuilder()
            .expireAfterAccess(entrylogMapAccessExpiryTimeInSeconds, TimeUnit.SECONDS)
            .maximumSize(maximumNumberOfActiveEntryLogs)
            .removalListener(new RemovalListener<Long, EntryLogAndLockTuple>() {
                @Override
                public void onRemoval(
                        RemovalNotification<Long, EntryLogAndLockTuple> expiredLedgerEntryLogMapEntry) {
                    onCacheEntryRemoval(expiredLedgerEntryLogMapEntry);
                }
            }).build(entryLogAndLockTupleCacheLoader);

    this.statsLogger = statsLogger;
    this.entryLogsPerLedgerCounter = new EntryLogsPerLedgerCounter(this.statsLogger);
}

From source file:com.app.server.WarDeployer.java

public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
    try {/*  w  w  w .  j a v  a  2s  .  c  o m*/
        this.serviceList = serviceList;
        this.serverConfig = serverConfig;
        this.mbeanServer = mbeanServer;
        this.scanDirectory = serverConfig.getDeploydirectory();
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {

                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/executorservices-config.xml")));
                } catch (Exception e) {
                    log.error("Could not able to load config xml rules ./config/executorservices-config.xml",
                            e);
                    //e.printStackTrace();
                }

            }
        });
        serverdigester = serverdigesterLoader.newDigester();
    } catch (Exception e1) {
        log.error("Could not create digester executorservices-config.xml", e1);
        //e1.printStackTrace();
    }
    try {
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {

                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/messagingclass-rules.xml")));
                } catch (FileNotFoundException e) {
                    log.error("Could not able to load config xml rules ./config/messagingclass-rules.xml", e);
                    //e.printStackTrace();
                }

            }
        });
        messagedigester = serverdigesterLoader.newDigester();
        DigesterLoader messagingdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {
                // TODO Auto-generated method stub
                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/messagingconfig-rules.xml")));
                } catch (Exception e) {
                    log.error("Could not able to load xml config file ./config/messagingclass-rules.xml", e);
                    e.printStackTrace();
                }

            }
        });
        Digester messagingdigester = messagingdigesterLoader.newDigester();
        messagingElem = (MessagingElem) messagingdigester
                .parse(new InputSource(new FileInputStream("./config/messaging.xml")));
        synchronized (messagingElem) {
            ConcurrentHashMap randomQueue = messagingElem.randomQueue;
            Set<String> randomQueueSet = randomQueue.keySet();
            Iterator<String> ite = randomQueueSet.iterator();
            while (ite.hasNext()) {
                Queue queue = (Queue) randomQueue.get(ite.next());
                ConcurrentHashMap randomqueuemap = (ConcurrentHashMap) messagingClassMap.get("RandomQueue");
                if (randomqueuemap == null) {
                    randomqueuemap = new ConcurrentHashMap();
                    messagingClassMap.put("RandomQueue", randomqueuemap);
                }
                CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) randomqueuemap
                        .get(queue.getQueuename());
                if (randomqueuelist == null)
                    randomqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList());
            }

            ConcurrentHashMap roundrobinQueue = messagingElem.roundrobinQueue;
            Set<String> roundrobinQueueSet = roundrobinQueue.keySet();
            ite = roundrobinQueueSet.iterator();
            while (ite.hasNext()) {
                Queue queue = (Queue) roundrobinQueue.get(ite.next());
                ConcurrentHashMap roundrobinqueuemap = (ConcurrentHashMap) messagingClassMap
                        .get("RoundRobinQueue");
                if (roundrobinqueuemap == null) {
                    roundrobinqueuemap = new ConcurrentHashMap();
                    messagingClassMap.put("RoundRobinQueue", roundrobinqueuemap);
                }
                CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) roundrobinqueuemap
                        .get(queue.getQueuename());
                if (randomqueuelist == null)
                    roundrobinqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList());
            }

            ConcurrentHashMap topicMap = messagingElem.topicMap;
            Set<String> topicSet = topicMap.keySet();
            Iterator<String> iter = topicSet.iterator();
            while (iter.hasNext()) {
                Topic topic = (Topic) topicMap.get(iter.next());
                ConcurrentHashMap topicmap = (ConcurrentHashMap) messagingClassMap.get("Topic");
                if (topicmap == null) {
                    topicmap = new ConcurrentHashMap();
                    messagingClassMap.put("Topic", topicmap);
                }
                CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) topicmap
                        .get(topic.getTopicname());
                if (randomqueuelist == null)
                    topicmap.put(topic.getTopicname(), new CopyOnWriteArrayList());
            }
            //log.info(messagingClassMap);
        }
    } catch (Exception e1) {
        log.error("", e1);
        //e1.printStackTrace();
    }

    try {
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {

                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/webxml-rules.xml")));
                } catch (FileNotFoundException e) {
                    log.error("could not able to load xml config rules ./config/webxml-rules.xml", e);
                    //e.printStackTrace();
                }

            }
        });
        webxmldigester = serverdigesterLoader.newDigester();
    } catch (Exception ex) {
        log.error("could not able to create web.xml digester", ex);
        // ex.printStackTrace();
    }
    log.info("initialized");
}