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.tinymediamanager.core.movie.MovieList.java

/**
 * Instantiates a new movie list.//  w  ww  .  j av  a 2s .c  om
 */
private MovieList() {
    // create all lists
    tagsObservable = ObservableCollections.observableList(new CopyOnWriteArrayList<String>());
    videoCodecsObservable = ObservableCollections.observableList(new CopyOnWriteArrayList<String>());
    audioCodecsObservable = ObservableCollections.observableList(new CopyOnWriteArrayList<String>());
    certificationsObservable = ObservableCollections.observableList(new CopyOnWriteArrayList<Certification>());

    // the tag listener: its used to always have a full list of all tags used in tmm
    tagListener = new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            // listen to changes of tags
            if ("tag".equals(evt.getPropertyName())) {
                Movie movie = (Movie) evt.getSource();
                updateTags(movie);
            }
            if (MEDIA_FILES.equals(evt.getPropertyName()) || MEDIA_INFORMATION.equals(evt.getPropertyName())) {
                Movie movie = (Movie) evt.getSource();
                updateMediaInformationLists(movie);
            }
            if (CERTIFICATION.equals(evt.getPropertyName())) {
                Movie movie = (Movie) evt.getSource();
                updateCertifications(movie);
            }
        }
    };

    movieSettings = MovieModuleManager.MOVIE_SETTINGS;
}

From source file:com.googlecode.starflow.engine.xml.NodeUtil.java

/**
 * ---/* w  w  w  . j  a v a2 s . c o m*/
 */
@SuppressWarnings("rawtypes")
public static List<FreeActElement> getActFreeActs(Element actEl) {
    List<FreeActElement> events = new CopyOnWriteArrayList<FreeActElement>();
    List list = actEl.selectNodes(StarFlowNames.ACT_FREE_ACT);
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
        Element el = (Element) iter.next();
        FreeActElement e = new FreeActElement();
        e.setId(el.attributeValue(StarFlowNames.ACT_FREE_ACT_ID));
        e.setName(el.attributeValue(StarFlowNames.ACT_FREE_ACT_NAME));
        e.setType(el.attributeValue(StarFlowNames.ACT_FREE_ACT_TYPE));
        events.add(e);
    }
    return events;
}

From source file:io.pivotal.strepsirrhini.chaoslemur.Destroyer.java

private void doDestroy(Task task) {
    List<Member> destroyedMembers = new CopyOnWriteArrayList<>();
    UUID identifier = UUID.randomUUID();

    this.logger.info("{} Beginning run...", identifier);

    this.infrastructure.getMembers().stream().map(member -> this.executorService.submit(() -> {
        if (this.fateEngine.shouldDie(member)) {
            try {
                this.logger.debug("{} Destroying: {}", identifier, member);

                if (this.dryRun) {
                    this.logger.info("{} Destroyed (Dry Run): {}", identifier, member);
                } else {
                    this.infrastructure.destroy(member);
                    this.logger.info("{} Destroyed: {}", identifier, member);
                }/*  w w w  .  java 2  s.  co m*/

                destroyedMembers.add(member);
            } catch (DestructionException e) {
                this.logger.warn("{} Destroy failed: {}", identifier, member, e);
            }
        }
    })).forEach(future -> {
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            this.logger.warn("{} Failed to destroy member", identifier, e);
        }
    });

    this.reporter.sendEvent(new Event(identifier, destroyedMembers));

    task.stop();
}

From source file:org.mariotaku.twidere.loader.TwitterAPIStatusesLoader.java

@SuppressWarnings("unchecked")
@Override/* w w w .j a  v a2  s  .  c  o  m*/
public final ListResponse<ParcelableStatus> loadInBackground() {
    final Context context = getContext();
    if (mAccountKey == null) {
        return ListResponse.getListInstance(new TwitterException("No Account"));
    }
    final ParcelableCredentials credentials = ParcelableCredentialsUtils.getCredentials(context, mAccountKey);
    if (credentials == null) {
        return ListResponse.getListInstance(new TwitterException("No Account"));
    }

    List<ParcelableStatus> data = getData();
    if (data == null) {
        data = new CopyOnWriteArrayList<>();
    }
    if (isFirstLoad() && getTabPosition() >= 0) {
        final List<ParcelableStatus> cached = getCachedData();
        if (cached != null) {
            data.addAll(cached);
            if (mComparator != null) {
                Collections.sort(data, mComparator);
            } else {
                Collections.sort(data);
            }
            return ListResponse.getListInstance(new CopyOnWriteArrayList<>(data));
        }
    }
    if (!isFromUser())
        return ListResponse.getListInstance(data);
    final Twitter twitter = TwitterAPIFactory.getTwitterInstance(context, credentials, true, true);
    if (twitter == null) {
        return ListResponse.getListInstance(new TwitterException("No Account"));
    }
    final List<? extends Status> statuses;
    final boolean noItemsBefore = data.isEmpty();
    final int loadItemLimit = mPreferences.getInt(KEY_LOAD_ITEM_LIMIT, DEFAULT_LOAD_ITEM_LIMIT);
    try {
        final Paging paging = new Paging();
        processPaging(credentials, loadItemLimit, paging);
        statuses = getStatuses(twitter, credentials, paging);
        if (!Utils.isOfficialCredentials(context, credentials)) {
            InternalTwitterContentUtils.getStatusesWithQuoteData(twitter, statuses);
        }
    } catch (final TwitterException e) {
        // mHandler.post(new ShowErrorRunnable(e));
        if (BuildConfig.DEBUG) {
            Log.w(LOGTAG, e);
        }
        return ListResponse.getListInstance(new CopyOnWriteArrayList<>(data), e);
    }

    final String[] statusIds = new String[statuses.size()];
    int minIdx = -1;
    int rowsDeleted = 0;
    for (int i = 0, j = statuses.size(); i < j; i++) {
        final Status status = statuses.get(i);
        if (minIdx == -1 || status.compareTo(statuses.get(minIdx)) < 0) {
            minIdx = i;
        }
        statusIds[i] = status.getId();
        if (deleteStatus(data, status.getId())) {
            rowsDeleted++;
        }
    }

    // Insert a gap.
    final boolean deletedOldGap = rowsDeleted > 0 && ArrayUtils.contains(statusIds, mMaxId);
    final boolean noRowsDeleted = rowsDeleted == 0;
    final boolean insertGap = minIdx != -1 && (noRowsDeleted || deletedOldGap) && !noItemsBefore
            && statuses.size() >= loadItemLimit && !mLoadingMore;
    for (int i = 0, j = statuses.size(); i < j; i++) {
        final Status status = statuses.get(i);
        final ParcelableStatus item = ParcelableStatusUtils.fromStatus(status, mAccountKey,
                insertGap && isGapEnabled() && minIdx == i);
        ParcelableStatusUtils.updateExtraInformation(item, credentials, mUserColorNameManager);
        data.add(item);
    }

    final SQLiteDatabase db = TwidereApplication.getInstance(context).getSQLiteDatabase();
    final ParcelableStatus[] array = data.toArray(new ParcelableStatus[data.size()]);
    for (int i = 0, size = array.length; i < size; i++) {
        final ParcelableStatus status = array[i];
        final boolean filtered = shouldFilterStatus(db, status);
        if (filtered) {
            if (!status.is_gap && i != size - 1) {
                data.remove(status);
            } else {
                status.is_filtered = true;
            }
        }
    }
    if (mComparator != null) {
        Collections.sort(data, mComparator);
    } else {
        Collections.sort(data);
    }
    saveCachedData(data);
    return ListResponse.getListInstance(new CopyOnWriteArrayList<>(data));
}

From source file:org.hawkular.listener.cache.InventoryHelperTest.java

@Test
public void shouldListEmptyTenantsForFeed() {
    // Data & mocks
    when(metricsService.getTenants())//from  w w  w .ja  v  a  2 s.co  m
            .thenReturn(Observable.just(new Tenant("t1"), new Tenant("t2"), new Tenant("t3")));
    when(metricsService.findMetricsWithFilters(anyString(), anyObject(), anyString()))
            .thenReturn(Observable.empty());

    // Test & assertions
    List<String> collectedTenants = new CopyOnWriteArrayList<>();
    InventoryHelper.listTenantsForFeed(metricsService, "some_feed").toList()
            .subscribe(tenants -> tenants.forEach(t -> collectedTenants.add(t.getId())), Throwables::propagate);
    Assert.assertTrue(collectedTenants.isEmpty());
}

From source file:com.castlemock.web.mock.rest.model.project.repository.RestProjectRepositoryImpl.java

/**
 * The post initialize method can be used to run functionality for a specific service. The method is called when
 * the method {@link #initialize} has finished successful.
 *
 * The method is responsible to validate the imported types and make certain that all the collections are
 * initialized.//  ww w.  j a va 2 s.c o m
 * @see #initialize
 * @see RestProject
 * @since 1.4
 */
@Override
protected void postInitiate() {
    for (RestProject restProject : collection.values()) {
        List<RestApplication> restApplications = new CopyOnWriteArrayList<RestApplication>();
        if (restProject.getApplications() != null) {
            restApplications.addAll(restProject.getApplications());
        }
        restProject.setApplications(restApplications);

        for (RestApplication restApplication : restProject.getApplications()) {
            List<RestResource> restResources = new CopyOnWriteArrayList<RestResource>();
            if (restApplication.getResources() != null) {
                restResources.addAll(restApplication.getResources());
            }
            restApplication.setResources(restResources);

            for (RestResource restResource : restApplication.getResources()) {
                List<RestMethod> restMethods = new CopyOnWriteArrayList<RestMethod>();
                if (restResource.getMethods() != null) {
                    restMethods.addAll(restResource.getMethods());
                }
                restResource.setMethods(restMethods);

                for (RestMethod restMethod : restResource.getMethods()) {
                    List<RestMockResponse> restMockResponses = new CopyOnWriteArrayList<RestMockResponse>();
                    if (restMethod.getMockResponses() != null) {
                        restMockResponses.addAll(restMethod.getMockResponses());
                    }
                    restMethod.setMockResponses(restMockResponses);

                    for (RestMockResponse restMockResponse : restMethod.getMockResponses()) {
                        List<HttpHeader> httpHeaders = new CopyOnWriteArrayList<HttpHeader>();
                        if (restMockResponse.getHttpHeaders() != null) {
                            httpHeaders.addAll(restMockResponse.getHttpHeaders());
                        }
                        restMockResponse.setHttpHeaders(httpHeaders);
                    }
                }
            }

        }
    }
}

From source file:net.sf.vfsjfilechooser.plaf.basic.BasicVFSDirectoryModel.java

/**
 *
 * @return//  w  w w . j a  v a2s .  c  o m
 */
public List<FileObject> getFiles() {
    aLock.readLock().lock();

    try {
        if (files != null) {
            return files;
        }

        files = new CopyOnWriteArrayList<FileObject>();
        directories = new CopyOnWriteArrayList<FileObject>();

        FileObject currentDir = filechooser.getCurrentDirectory();
        AbstractVFSFileSystemView v = filechooser.getFileSystemView();
        directories.add(v.createFileObject(currentDir, ".."));

        for (FileObject f : fileCache) {
            if (filechooser.isTraversable(f)) {
                directories.add(f);
            } else {
                files.add(f);
            }
        }

        return files;
    } finally {
        aLock.readLock().unlock();
    }
}

From source file:org.ulyssis.ipp.processor.Processor.java

public Processor(final ProcessorOptions options) {
    Database.setDatabaseURI(options.getDatabaseUri());
    try (Connection connection = Database.createConnection(EnumSet.of(READ_WRITE))) {
        if (options.shouldClearDb()) {
            Database.clearDb(connection);
        }//from  w ww  .j a v  a 2 s  .co  m
        Database.initDb(connection);
        connection.commit();
    } catch (SQLException e) {
        LOG.fatal("Error initializing database!", e);
    }
    URI uri = options.getRedisUri();
    this.eventQueue = new LinkedBlockingQueue<>();
    this.eventCallbacks = new ConcurrentHashMap<>();
    this.onStartedCallbacks = new CopyOnWriteArrayList<>();
    this.readerListeners = new ArrayList<>();
    this.threads = new ArrayList<>();
    // TODO: Move status reporting and processing of commands to ZeroMQ?
    // Also: post some stuff to a log in the db?
    this.statusReporter = new StatusReporter(uri, Config.getCurrentConfig().getStatusChannel());
    this.commandProcessor = new CommandProcessor(uri, Config.getCurrentConfig().getControlChannel(),
            statusReporter);
    initCommandProcessor();
    snapshot = new Snapshot(Instant.EPOCH);
    if (!restoreFromDb()) {
        registerInitialTags();
    }
}

From source file:com.amazonaws.AmazonWebServiceClient.java

/**
 * Constructs a new AmazonWebServiceClient object using the specified
 * configuration and request metric collector.
 *
 * @param clientConfiguration// w ww .jav a2 s  .c o m
 *            The client configuration for this client.
 * @param requestMetricCollector
 *            optional request metric collector to be used at the http
 *            client level; can be null.
 */
public AmazonWebServiceClient(ClientConfiguration clientConfiguration,
        RequestMetricCollector requestMetricCollector) {
    this.clientConfiguration = clientConfiguration;
    client = new AmazonHttpClient(clientConfiguration, requestMetricCollector);
    requestHandler2s = new CopyOnWriteArrayList<RequestHandler2>();
}

From source file:com.googlecode.vfsjfilechooser2.plaf.basic.BasicVFSDirectoryModel.java

/**
 *
 * @return//from  www .  jav  a  2s.c om
 */
public List<FileObject> getFiles() {
    aLock.readLock().lock();

    try {
        if (files != null) {
            return files;
        }

        files = new CopyOnWriteArrayList<FileObject>();
        directories = new CopyOnWriteArrayList<FileObject>();

        FileObject currentDir = filechooser.getCurrentDirectoryObject();
        AbstractVFSFileSystemView v = filechooser.getFileSystemView();
        directories.add(v.createFileObject(currentDir, ".."));

        for (FileObject f : fileCache) {
            if (filechooser.isTraversable(f)) {
                directories.add(f);
            } else {
                files.add(f);
            }
        }

        return files;
    } finally {
        aLock.readLock().unlock();
    }
}