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.cyanogenmod.changelog.ChangelogActivity.java

/**
 * Utility method./*  ww w. j a va2s.c  o m*/
 */
private void init() {
    // Setup SwipeRefreshLayout
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
    // Setup refresh listener which triggers new data loading
    mSwipeRefreshLayout.setOnRefreshListener(this);
    // Color scheme of the refresh spinner
    mSwipeRefreshLayout.setColorSchemeResources(R.color.color_primary_dark, R.color.color_accent);
    // Setup RecyclerView
    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    // Setup divider for RecyclerView items
    mRecyclerView.addItemDecoration(new Divider(this));
    // Setup item animator
    mRecyclerView.setItemAnimator(null); // Disable to prevent view blinking when refreshing
    // Setup and initialize RecyclerView adapter
    mAdapter = new ChangelogAdapter(this, new CopyOnWriteArrayList<Change>());
    mRecyclerView.setAdapter(mAdapter);
    // Setup and initialize info dialog
    String message = String.format(Locale.getDefault(), "%s %s\n\n%s %s\n\n%s %s\n\n%s %s",
            getString(R.string.dialog_device_name), Device.DEVICE, getString(R.string.dialog_version),
            Device.CM_VERSION, getString(R.string.dialog_build_date), Device.BUILD_DATE,
            getString(R.string.dialog_update_channel), Device.CM_RELEASE_CHANNEL);
    View infoDialog = getLayoutInflater().inflate(R.layout.info_dialog, mRecyclerView, false);
    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_InfoDialog).setView(infoDialog)
            .setPositiveButton(R.string.dialog_ok, null);
    TextView dialogMessage = (TextView) infoDialog.findViewById(R.id.info_dialog_message);
    dialogMessage.setText(message);
    mInfoDialog = builder.create();
}

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

@SuppressWarnings("unchecked")
@Override//from   ww  w . j a  va 2 s .  c om
public final ListResponse<ParcelableStatus> loadInBackground() {
    final Context context = getContext();
    if (mAccountKey == null) {
        return ListResponse.getListInstance(new MicroBlogException("No Account"));
    }
    final ParcelableCredentials credentials = ParcelableCredentialsUtils.getCredentials(context, mAccountKey);
    if (credentials == null) {
        return ListResponse.getListInstance(new MicroBlogException("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 MicroBlog twitter = MicroBlogAPIFactory.getInstance(context, credentials, true, true);
    if (twitter == null) {
        return ListResponse.getListInstance(new MicroBlogException("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);
    } catch (final MicroBlogException e) {
        // mHandler.post(new ShowErrorRunnable(e));
        mException.set(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:com.l2jfree.gameserver.model.entity.events.AutomatedTvT.java

private AutomatedTvT() {
    tpm = ThreadPoolManager.getInstance();
    status = STATUS_NOT_IN_PROGRESS;/*from w ww  .j av a 2s. c om*/
    announced = 0;
    // This has no maximum bound, thus configuration changes will not crash anything
    participants = new CopyOnWriteArrayList<L2Player>();
    registered = new CopyOnWriteArrayList<Integer>();
    eventPlayers = new FastMap<Integer, Participant>(Config.AUTO_TVT_PARTICIPANTS_MAX);
    eventTeams = null;
    task = new AutoEventTask();
    taskDuring = new AutoReviveTask();
    reviver = null;
    buildCountArray();
    active = Config.AUTO_TVT_ENABLED;
    if (active)
        tpm.scheduleGeneral(task, Config.AUTO_TVT_DELAY_INITIAL_REGISTRATION);
    _log.info("AutomatedTvT: initialized.");
}

From source file:com.neophob.sematrix.glue.Collector.java

/**
 * Instantiates a new collector./*from  w  w w .  ja v a 2 s.  co  m*/
 */
private Collector() {
    allVisuals = new CopyOnWriteArrayList<Visual>();

    this.nrOfScreens = 0;
    ioMapping = new CopyOnWriteArrayList<OutputMapping>();
    initialized = false;

    selectedPresent = 0;
    present = new CopyOnWriteArrayList<PresentSettings>();
    for (int n = 0; n < NR_OF_PRESENT_SLOTS; n++) {
        present.add(new PresentSettings());
    }

    pixelControllerShufflerSelect = new PixelControllerShufflerSelect();
    pixelControllerShufflerSelect.initAll();
}

From source file:com.connectsdk.discovery.provider.ZeroconfDiscoveryProvider.java

public ZeroconfDiscoveryProvider(Context context) {
    foundServices = new ConcurrentHashMap<String, ServiceDescription>(8, 0.75f, 2);

    serviceListeners = new CopyOnWriteArrayList<DiscoveryProviderListener>();
    serviceFilters = new ArrayList<JSONObject>();

    try {/*from  w  ww. ja va  2 s .  c  o m*/
        srcAddress = Util.getIpAddress(context);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

From source file:org.rifidi.edge.epcglobal.aleread.wrappers.RifidiECSpec.java

/**
 * Constructor.//w w  w. ja  v a 2s  . c  o  m
 * 
 * @param name
 * @param spec
 * @param esper
 * @param rifidiBoundarySpec
 * @param readers
 * @param primarykeys
 * @param reports
 * @throws InvalidURIExceptionResponse
 * @throws ECSpecValidationExceptionResponse
 */
public RifidiECSpec(final String name, final ECSpec spec, final EPServiceProvider esper,
        final RifidiBoundarySpec rifidiBoundarySpec, final Collection<String> readers,
        final Collection<String> primarykeys, final Collection<RifidiReport> reports) {
    this.startLock = new ReentrantLock();
    this.rifidiBoundarySpec = rifidiBoundarySpec;
    this.spec = spec;
    this.name = name;
    this.esper = esper;
    this.readers = new HashSet<String>();
    this.readers.addAll(readers);
    // configure the report sender
    this.sender = new ReportSender(reports, name, spec);

    // collect the primary keys
    this.primarykeys = new HashSet<String>();
    this.primarykeys.addAll(primarykeys);
    if (this.primarykeys.isEmpty()) {
        this.primarykeys.add("epc");
    }
    this.subscriptionURIs = new CopyOnWriteArrayList<String>();

    startStatementControllers = new ArrayList<StatementController>();
    stopStatementControllers = new ArrayList<StatementController>();
    //      collectionStatements = new ArrayList<EPStatement>();
    //      collectionStatements.add();
    this.esper.getEPAdministrator()
            .createEPL("insert into ecspec_" + name
                    + " select * from ReadCycle[select * from tags] where readerID in ("
                    + assembleLogicalReader(this.readers) + ") ");
    // add a timer if we got triggers
    if (rifidiBoundarySpec.getStartTriggers().size() != 0 || rifidiBoundarySpec.getStopTriggers() != null) {
        timer = new Timer(rifidiBoundarySpec.getStartTriggers(), rifidiBoundarySpec.getStopTriggers(),
                this.esper);
    }
    // TODO: When data available needs to be added ASAP!!!
    if (rifidiBoundarySpec.isWhenDataAvailable()) {
        logger.fatal("'When data available' not yet implemented!");
    }
    if (rifidiBoundarySpec.getDuration() > 0) {
        logger.debug("Initializing duration timing with duration=" + rifidiBoundarySpec.getDuration());
        DurationTimingStatement durationTimingStatement = new DurationTimingStatement(
                this.esper.getEPAdministrator(), "ecspec_" + name, rifidiBoundarySpec.getDuration(),
                this.primarykeys);
        durationTimingStatement.registerSignalListener(this);
        stopStatementControllers.add(durationTimingStatement);
    }
    // if (rifidiBoundarySpec.getStableSetInterval() > 0) {
    // logger
    // .debug("Initializing 'stable set interval' timing with interval="
    // + rifidiBoundarySpec.getStableSetInterval());
    // StableSetTimingStatement stableSetTimingStatement = new
    // StableSetTimingStatement(
    // esper.getEPAdministrator(), rifidiBoundarySpec
    // .getStableSetInterval(), primarykeys);
    // stableSetTimingStatement.registerSignalListener(this);
    // stopStatementControllers.add(stableSetTimingStatement);
    // }
    // if (rifidiBoundarySpec.getStopTriggers().size() > 0) {
    // // TODO: create triggers
    // StopEventTimingStatement stopEventTimingStatement = new
    // StopEventTimingStatement(
    // esper.getEPAdministrator(), primarykeys);
    // stopEventTimingStatement.registerSignalListener(this);
    // stopStatementControllers.add(stopEventTimingStatement);
    // }
    if (rifidiBoundarySpec.getStartTriggers().size() > 0) {
        instantStart = false;
        StartEventStatement startEventStatement = new StartEventStatement(this.esper.getEPAdministrator());
        startEventStatement.registerSignalListener(this);
        startEventStatement.start();
        startStatementControllers.add(startEventStatement);
    }
    if (rifidiBoundarySpec.getRepeatInterval() > 0) {
        IntervalTimingStatement intervalTimingStatement = new IntervalTimingStatement(
                this.esper.getEPAdministrator(), rifidiBoundarySpec.getRepeatInterval());
        intervalTimingStatement.registerSignalListener(this);
        startStatementControllers.add(intervalTimingStatement);
    }
}

From source file:com.castlemock.web.mock.soap.model.project.repository.SoapProjectRepositoryImpl.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 v  a2 s  .  c o m*/
 * @see #initialize
 * @see SoapProject
 * @since 1.4
 */
@Override
protected void postInitiate() {
    for (SoapProject soapProject : collection.values()) {
        List<SoapPort> soapPorts = new CopyOnWriteArrayList<SoapPort>();
        if (soapProject.getPorts() != null) {
            soapPorts.addAll(soapProject.getPorts());
        }
        soapProject.setPorts(soapPorts);

        for (SoapPort soapPort : soapProject.getPorts()) {
            List<SoapOperation> soapOperations = new CopyOnWriteArrayList<SoapOperation>();
            if (soapPort.getOperations() != null) {
                soapOperations.addAll(soapPort.getOperations());
            }
            soapPort.setOperations(soapOperations);

            for (SoapOperation soapOperation : soapPort.getOperations()) {
                List<SoapMockResponse> soapMockResponses = new CopyOnWriteArrayList<SoapMockResponse>();
                if (soapOperation.getMockResponses() != null) {
                    soapMockResponses.addAll(soapOperation.getMockResponses());
                }
                soapOperation.setMockResponses(soapMockResponses);

                for (SoapMockResponse soapMockResponse : soapOperation.getMockResponses()) {
                    List<HttpHeader> httpHeaders = new CopyOnWriteArrayList<HttpHeader>();
                    if (soapMockResponse.getHttpHeaders() != null) {
                        httpHeaders.addAll(soapMockResponse.getHttpHeaders());
                    }
                    soapMockResponse.setHttpHeaders(httpHeaders);
                }
            }

        }
    }
}

From source file:org.springsource.ide.eclipse.commons.browser.javafx.JavaFxBrowserManager.java

/**
 * Calls Javascript functions <i>to</i> the browser, refreshing the browser
 * when all calls have completed./*from w ww  .  j  a  v  a  2 s.c  om*/
 * @param functions
 */
public void callOnBrowser(final Collection<IEclipseToBrowserFunction> functions) {
    final Collection<IEclipseToBrowserFunction> waitingFunctions = new CopyOnWriteArrayList<IEclipseToBrowserFunction>();
    IEclipseToBrowserFunction.Callback callback = new IEclipseToBrowserFunction.Callback() {
        @Override
        public void ready(IEclipseToBrowserFunction function) {
            waitingFunctions.remove(function);
            if (waitingFunctions.isEmpty() && !disposed) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        JSObject js = (JSObject) getEngine().executeScript("window");
                        for (IEclipseToBrowserFunction provider : functions) {
                            js.call(provider.getFunctionName(), (Object[]) provider.getArguments());
                        }
                        getView().requestLayout();
                        getView().setVisible(true);
                        if (DEBUG) {
                            printPageHtml();
                        }
                    }
                });
            }
        }
    };
    for (IEclipseToBrowserFunction function : functions) {
        if (!function.isReady()) {
            waitingFunctions.add(function);
            function.setCallback(callback);
        }
    }
    callback.ready(null);
}

From source file:de.dfki.asr.compass.model.SceneNode.java

private void initializeFields() {
    name = "";//from   w w  w.j a v  a 2s .  c  o m
    components = new CopyOnWriteArrayList<>();
    children = new CopyOnWriteArrayList<>();
    visible = true;
    localOrientation = new Orientation();
    selectable3d = true;
    localTranslation = new Vector3f();
    localScale = 1.f;
    indexInParentChildren = 0;
}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

private NicosClient() {
    // private constructor -> Singleton
    Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
    callbackHandlers = Collections.synchronizedList(new CopyOnWriteArrayList<NicosCallbackHandler>());
    socket = null;//from   ww w .  ja v a2  s. co  m
    eventSocket = null;
    connected = false;
    disconnecting = false;
    last_reqno = null;
    viewonly = true;
    user_level = -1;
    MessageDigest md5 = getMD5();
    if (md5 != null) {
        client_id = getMD5().digest(getUniqueID().getBytes());
    }

    // Add debug printer for signals.
    // callbackHandlers.add(new SignalDebugPrinter());
    Unpickler.registerConstructor("nicos.utils", "readonlylist", new ReadOnlyListConstructor());
    Unpickler.registerConstructor("nicos.utils", "readonlydict", new ReadOnlyDictConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "ConfigurationError",
            new ConfigurationErrorConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "CommunicationError",
            new CommunicationErrorConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "NicosError", new NicosErrorConstructor());
    Unpickler.registerConstructor("nicos.core.errors", "InvalidValueError", new InvalidValueErrorConstructor());
    Unpickler.registerConstructor("__builtin__", "str", new strErrorConstructor());
}