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:android.bus.EventBus.java

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
    Class<?> eventType = subscriberMethod.eventType;
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);
    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<Subscription>();
        subscriptionsByEventType.put(eventType, subscriptions);
    }// ww  w .  java2s.  co m
    // FIXME ???
    // else {
    // if (subscriptions.contains(newSubscription)) {
    // throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
    // + eventType);
    // }
    // }

    // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
    // subscriberMethod.method.setAccessible(true);

    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<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<Class<?>>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);

    if (sticky) {
        if (eventInheritance) {
            // Existing sticky events of all subclasses of eventType have to be considered.
            // Note: Iterating over all events may be inefficient with lots of sticky events,
            // thus data structure should be changed to allow a more efficient lookup
            // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
            Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry<Class<?>, Object> entry : entries) {
                Class<?> candidateEventType = entry.getKey();
                if (eventType.isAssignableFrom(candidateEventType)) {
                    Object stickyEvent = entry.getValue();
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            Object stickyEvent = stickyEvents.get(eventType);
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

From source file:com.intel.xdk.multitouch.MultiTouch.java

public void enableMultitouch() {
    this.multitouchQueue = new CopyOnWriteArrayList<String>();
    this.multitouchMap = new SparseArray<String>();
    this.isMultitouchEnabled = true;
}

From source file:com.netflix.config.ConcurrentMapConfiguration.java

protected void setPropertyImpl(String key, Object value) {
    if (isDelimiterParsingDisabled()) {
        map.put(key, value);/*from w ww .  ja va  2 s .  co  m*/
    } else if ((value instanceof String) && ((String) value).indexOf(getListDelimiter()) < 0) {
        map.put(key, value);
    } else {
        Iterator it = PropertyConverter.toIterator(value, getListDelimiter());
        List<Object> list = new CopyOnWriteArrayList<Object>();
        while (it.hasNext()) {
            list.add(it.next());
        }
        if (list.size() == 1) {
            map.put(key, list.get(0));
        } else {
            map.put(key, list);
        }
    }
}

From source file:org.rdv.datapanel.AbstractDataPanel.java

/**
 * Initialize the list of channels and units. Set parameters to defaults.
 * /*w  w w.j  a va 2s . co  m*/
 * @since  1.1
 */
public AbstractDataPanel() {
    /*
     * We use a copy on write array list so traversals are thread safe. This
     * allows the iterators used for posting of data to be inherintly thread
     * safe at the cost of the time taken to add/remove channels.
     */
    channels = new CopyOnWriteArrayList<String>();

    lowerThresholds = new Hashtable<String, String>();
    upperThresholds = new Hashtable<String, String>();

    time = 0;
    timeScale = 1;
    state = RBNBController.STATE_DISCONNECTED;

    attached = true;

    maximized = false;

    paused = false;

    showChannelsInTitle = true;

    properties = new Properties();
}

From source file:ypcnv.converter.mainFrame.MainFrame.java

/**
 * Check configurations for nulls, arrange them, etc.
 * @param confsList - configurations to be processed.
 *///  w  w w  .  j a  v a 2s. c  o  m
private void refactorConfigurations(ArrayList<DataSourceConf> confsList) {
    CopyOnWriteArrayList<DataSourceConf> confs = new CopyOnWriteArrayList<DataSourceConf>();
    confs.addAll(confsList);

    srcObjectConfig = null;
    dstObjectConfig = null;

    for (DataSourceConf config : confs) {
        Side side = config.getSide();
        if (side == null) {
            side = Side.heath;
        }
        switch (side) {
        case source:
            srcObjectConfig = new DataSourceConf(config);
            confsList.remove(config);
            break;
        case destination:
            dstObjectConfig = new DataSourceConf(config);
            confsList.remove(config);
            break;
        }
    }

    int quantityOfWantedDataSources = 2;
    for (int idx = 0; idx < confs.size() && idx < quantityOfWantedDataSources && confs.size() > 0; idx++) {
        Iterator<DataSourceConf> iter = confs.iterator();
        while (iter.hasNext()) {
            DataSourceConf conf = iter.next();
            if (srcObjectConfig == null) {
                srcObjectConfig = conf;
                confsList.remove(conf);
            } else if (dstObjectConfig == null) {
                dstObjectConfig = conf;
                confsList.remove(conf);
            }

        }
    }

    if (srcObjectConfig == null) {
        srcObjectConfig = new DataSourceConf(null, null, null);
    }
    if (dstObjectConfig == null) {
        dstObjectConfig = new DataSourceConf(null, null, null);
    }

    confsList = new ArrayList<DataSourceConf>();
    confsList.add(srcObjectConfig);
    confsList.add(dstObjectConfig);

}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferStatusUpdater.java

/**
 * Registers a {@link TransferListener} to a transfer.
 *
 * @param id id of the transfer//  w  ww  .  ja va  2 s.  c om
 * @param listener a listener object
 */
static void registerListener(int id, TransferListener listener) {
    if (listener == null) {
        throw new IllegalArgumentException("Listener can't be null");
    }
    synchronized (LISTENERS) {
        List<TransferListener> list = LISTENERS.get(id);
        if (list == null) {
            list = new CopyOnWriteArrayList<TransferListener>();
            list.add(listener);
            LISTENERS.put(id, list);
        } else {
            // don't add the same listener more than once
            if (!list.contains(listener)) {
                list.add(listener);
            }
        }
    }
}

From source file:feup.pfaria.jenkins.plugins.filtereddashboardview.FilteredDashboardView.java

/**
 * Forces some default values/*  w w  w  .  j  av a  2 s.c  om*/
 * Refreshes Jobs and Builds that suffered changes
 *
 * @return this View
 */
protected Object readResolve() {

    if (getBuildsLimit == 0)
        getBuildsLimit = 250;

    if (fontSize == 0)
        fontSize = 16;

    if (buildHistorySize == 0)
        buildHistorySize = 16;

    if (buildQueueSize == 0)
        buildQueueSize = 10;

    if (statusButtonSize == null)
        statusButtonSize = "";

    if (layoutHeightRatio == null)
        layoutHeightRatio = "6040";

    if (projectBuildTableSize == 0)
        projectBuildTableSize = 5;

    if (selectedViews == null) {
        this.selectedViews = new HashMap<String, Boolean>();
    }

    //Forces a reset on the Maps, to ensure changes are apllied
    this.jobsInProjectMap = new TreeMap<String, ArrayList<String>>();
    this.jobsMap = new TreeMap<String, JobData>();

    //if (views == null) {
    views = new CopyOnWriteArrayList<View>();
    //}

    if (views.isEmpty()) {
        // preserve the non-empty invariant
        views.add(new ListView("Default", this));
    }

    return this;
}

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

@Test
@Ignore/*from  w ww  .j a va  2  s . c o  m*/
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");
    }
    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.ibm.watson.app.common.services.impl.BluemixServicesBinder.java

protected static <T extends BluemixConfiguredService> void registerBluemixService(Class<T> iface,
        BluemixConfiguredService impl) {
    Objects.requireNonNull(impl);

    List<BluemixConfiguredService> services = AVAILABLE_SERVICES.get(iface);
    if (services == null) {
        final List<BluemixConfiguredService> newServicesList = new CopyOnWriteArrayList<>();
        services = AVAILABLE_SERVICES.putIfAbsent(iface, newServicesList);
        if (services == null) {
            services = newServicesList;//  w w w . jav  a2 s .co  m
        }
    }
    services.add(impl);
}

From source file:org.omnaest.utils.operation.foreach.ForEachOperation.java

/**
 * @see #execute(Operation...)//w  ww .j a  v a2  s .co m
 * @param operations
 * @return
 */
@SuppressWarnings("unchecked")
private Result<V> executeMultiThreaded(final Operation<V, E>... operations) {
    //
    final List<V> retlist = new CopyOnWriteArrayList<V>();

    //
    final FutureTaskManager futureTaskManagerExecution = new FutureTaskManager(
            this.executorServiceForParallelExecution);
    final FutureTaskManager futureTaskManagerIteration = new FutureTaskManager(
            this.executorServiceForParallelIteration);

    //    
    for (Iterable<E> iterable : this.iterables) {
        if (iterable != null) {
            //
            final Iterator<E> iterator = iterable.iterator();
            final Runnable runnableForIteration = new Runnable() {
                @Override
                public void run() {
                    //
                    try {
                        while (true) {
                            //
                            final E element = iterator.next();

                            //
                            for (final Operation<V, E> operation : operations) {
                                if (operation != null) {
                                    if (futureTaskManagerExecution.hasExecutorService()) {
                                        futureTaskManagerExecution.submitAndManage(new Callable<V>() {
                                            @Override
                                            public V call() throws Exception {
                                                return operation.execute(element);
                                            }
                                        });
                                    } else {
                                        retlist.add(operation.execute(element));
                                    }
                                }
                            }
                        }

                    } catch (NoSuchElementException e) {
                    }

                    //
                    if (futureTaskManagerExecution.hasExecutorService()) {
                        retlist.addAll(
                                (List<V>) futureTaskManagerExecution.waitForAllTasksToFinish().getResult());
                    }
                }
            };

            //
            if (futureTaskManagerIteration.hasExecutorService()) {
                //
                for (int ii = 1; ii <= this.numberOfThreadsForParallelIteration; ii++) {
                    futureTaskManagerIteration.submitAndManage(runnableForIteration);
                }

                //
                futureTaskManagerIteration.waitForAllTasksToFinish();
            } else {
                runnableForIteration.run();
            }
        }
    }

    //
    return new Result<V>(org.apache.commons.collections.ListUtils.unmodifiableList(retlist));
}