Example usage for java.util Collections synchronizedList

List of usage examples for java.util Collections synchronizedList

Introduction

In this page you can find the example usage for java.util Collections synchronizedList.

Prototype

public static <T> List<T> synchronizedList(List<T> list) 

Source Link

Document

Returns a synchronized (thread-safe) list backed by the specified list.

Usage

From source file:org.jcf.ConnectionImpl.java

public Collection<String> getJoinedRooms(String user) {
    if (xMPPconnection == null)
        throw new JCFException("call connect first");
    Iterator<String> i = MultiUserChat.getJoinedRooms(xMPPconnection, user);
    List<String> l = Collections.synchronizedList(new ArrayList<String>());
    while (i.hasNext())
        l.add(new String(i.next()));
    return l;/*from  ww w .j a  va 2 s  . co m*/
}

From source file:aarddict.android.ArticleViewActivity.java

@Override
void initUI() {/*from w ww .j av a  2  s .  c  o m*/
    this.scrollPositionsH = Collections.synchronizedMap(new HashMap<Article, ScrollXY>());
    this.scrollPositionsV = Collections.synchronizedMap(new HashMap<Article, ScrollXY>());
    loadAssets();

    if (DeviceInfo.EINK_SCREEN) {
        useAnimation = false;
        setContentView(R.layout.eink_article_view);
        articleView = (ArticleView) findViewById(R.id.EinkArticleView);
        N2EpdController.n2MainActivity = this;
        EinkScreen.ResetController(2, articleView); // force full screen
                                                    // refresh when changing
                                                    // articles
    }
    // Setup animations only on non-eink screens
    else {
        useAnimation = true;
        fadeOutAnimation = new AlphaAnimation(1f, 0f);
        fadeOutAnimation.setDuration(600);
        fadeOutAnimation.setAnimationListener(new AnimationAdapter() {
            public void onAnimationEnd(Animation animation) {
                Button nextButton = (Button) findViewById(R.id.NextButton);
                nextButton.setVisibility(Button.GONE);
            }
        });

        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.article_view);
        articleView = (ArticleView) findViewById(R.id.ArticleView);
    }

    timer = new Timer();

    backItems = Collections.synchronizedList(new LinkedList<HistoryItem>());

    if (android.os.Build.VERSION.SDK_INT >= 11) {
        try {
            showFindDialogMethod = articleView.getClass().getMethod("showFindDialog", String.class,
                    boolean.class);
        } catch (NoSuchMethodException e1) {
            Log.d(TAG, "showFindDialog method not found");
        }

    }

    articleView.setOnScrollListener(new ArticleView.ScrollListener() {
        public void onScroll(int l, int t, int oldl, int oldt) {
            saveScrollPos(l, t);
        }
    });

    articleView.getSettings().setJavaScriptEnabled(true);
    articleView.addJavascriptInterface(new SectionMatcher(), "matcher");
    articleView.addJavascriptInterface(articleView, "scrollControl");

    articleView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(TAG + ".js", String.format("[%s]: %s", url, message));
            result.cancel();
            return true;
        }

        public void onProgressChanged(WebView view, int newProgress) {
            Log.d(TAG, "Progress: " + newProgress);
            setProgress(5000 + newProgress * 50);
        }
    });

    articleView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d(TAG, "Page finished: " + url);
            currentTask = null;
            String section = null;

            if (url.contains("#")) {
                LookupWord lookupWord = LookupWord.splitWord(url);
                section = lookupWord.section;
                if (backItems.size() > 0) {
                    HistoryItem currentHistoryItem = backItems.get(backItems.size() - 1);
                    HistoryItem h = new HistoryItem(currentHistoryItem);
                    h.article.section = section;
                    backItems.add(h);
                }
            } else if (backItems.size() > 0) {
                Article current = backItems.get(backItems.size() - 1).article;
                section = current.section;
            }
            if (!restoreScrollPos()) {
                goToSection(section);
            }
            updateNextButtonVisibility();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            Log.d(TAG, "URL clicked: " + url);
            String urlLower = url.toLowerCase();
            if (urlLower.startsWith("http://") || urlLower.startsWith("https://")
                    || urlLower.startsWith("ftp://") || urlLower.startsWith("sftp://")
                    || urlLower.startsWith("mailto:")) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(browserIntent);
            } else {
                if (currentTask == null) {
                    currentTask = new TimerTask() {
                        public void run() {
                            try {
                                Article currentArticle = backItems.get(backItems.size() - 1).article;
                                try {
                                    Iterator<Entry> currentIterator = dictionaryService.followLink(url,
                                            currentArticle.volumeId);
                                    List<Entry> result = new ArrayList<Entry>();
                                    while (currentIterator.hasNext() && result.size() < 20) {
                                        result.add(currentIterator.next());
                                    }
                                    showNext(new HistoryItem(result));
                                } catch (ArticleNotFound e) {
                                    showMessage(getString(R.string.msgArticleNotFound, e.word.toString()));
                                }
                            } catch (Exception e) {
                                StringBuilder msgBuilder = new StringBuilder(
                                        "There was an error following link ").append("\"").append(url)
                                                .append("\"");
                                if (e.getMessage() != null) {
                                    msgBuilder.append(": ").append(e.getMessage());
                                }
                                final String msg = msgBuilder.toString();
                                Log.e(TAG, msg, e);
                                showError(msg);
                            }
                        }
                    };
                    try {
                        timer.schedule(currentTask, 0);
                    } catch (Exception e) {
                        Log.d(TAG, "Failed to schedule task", e);
                    }
                }
            }
            return true;
        }
    });
    final Button nextButton = (Button) findViewById(R.id.NextButton);
    nextButton.getBackground().setAlpha(180);
    nextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (nextButton.getVisibility() == View.VISIBLE) {
                updateNextButtonVisibility();
                nextArticle();
                updateNextButtonVisibility();
            }
        }
    });
    articleView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            updateNextButtonVisibility();
            return false;
        }
    });

    setProgressBarVisibility(true);
}

From source file:org.beepcore.beep.core.ChannelImpl.java

ChannelImpl(String profile, String number, RequestHandler handler, boolean tuningReset, SessionImpl session) {
    this.profile = profile;
    this.encoding = Constants.ENCODING_DEFAULT;
    this.number = number;
    this.setRequestHandler(handler, tuningReset);
    this.session = session;
    sentSequence = 0;/*from  w  ww  .ja va2s .c om*/
    recvSequence = 0;
    lastMessageSent = 1;

    pendingSendMessages = new LinkedList();
    sentMSGQueue = Collections.synchronizedList(new LinkedList());
    recvMSGQueue = new LinkedList();
    recvReplyQueue = new LinkedList();
    state = STATE_INITIALIZED;
    recvWindowUsed = new AtomicInteger(0);
    recvWindowFreed = new AtomicInteger(0);
    recvWindowSize = new AtomicInteger(DEFAULT_WINDOW_SIZE);
    peerWindowSize = new AtomicInteger(DEFAULT_WINDOW_SIZE);
}

From source file:org.piwik.sdk.TestDispatcher.java

@Test
public void testBatchDispatch() throws Exception {
    final Tracker tracker = createTracker();
    tracker.setDispatchInterval(1500);/*  w ww  .  j  a  v a  2s. co  m*/

    final int threadCount = 5;
    final int queryCount = 5;
    final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>());
    launchTestThreads(tracker, threadCount, queryCount, createdEvents);
    Thread.sleep(1000);
    assertEquals(threadCount * queryCount, createdEvents.size());
    assertEquals(0, tracker.getDispatcher().getDryRunOutput().size());
    Thread.sleep(1000);

    checkForMIAs(threadCount * queryCount, createdEvents, tracker.getDispatcher().getDryRunOutput());
}

From source file:org.csstudio.utility.batik.SVGHandler.java

public SVGHandler(final SVGDocument doc, final Display display) {
    swtDisplay = display;/*from w  w w .  j a va 2 s  .  c o m*/
    useCache = Preferences.getUseCache();
    imageBuffer = Collections.synchronizedList(new ArrayList<Image>());
    maxBufferSize = Preferences.getCacheMaxSize();

    listener = new Listener();
    userAgent = createUserAgent();
    renderingHints = new RenderingHints(null);

    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    originalSVGDocument = (SVGDocument) DOMUtilities.deepCloneDocument(doc, impl);
    bridgeContext = createBridgeContext((SVGOMDocument) originalSVGDocument);
    isDynamicDocument = bridgeContext.isDynamicDocument(originalSVGDocument);
    // As we update the DOM, it has to be considered as dynamic
    bridgeContext.setDynamicState(BridgeContext.DYNAMIC);
    builder = new DynamicGVTBuilder();
    // Build to calculate original dimension
    gvtRoot = builder.build(bridgeContext, originalSVGDocument);
    originalDimension = bridgeContext.getDocumentSize();

    svgDocument = (SVGDocument) createWrapper(originalSVGDocument);
    builder.build(bridgeContext, svgDocument);
    buildElementsToUpdateList(bridgeContext, svgDocument);
    setAnimationLimitingFPS(10);
}

From source file:kmi.taa.core.Crawler.java

public void crawlAll(TreeMap<Integer, String> targetUrls, String service, String proxy, String otfile) {
    SortedSet<Integer> results = Collections.synchronizedSortedSet(new TreeSet<Integer>());
    ExecutorService pool = Executors.newFixedThreadPool(100);

    int howManyUrls = targetUrls.size();
    System.out.println("total " + howManyUrls + " to be processed");

    List<String> output = Collections.synchronizedList(new ArrayList<String>());
    for (Integer targetId : targetUrls.navigableKeySet()) {
        String uri = targetUrls.get(targetId);
        pool.execute(new Explorer(targetId, uri, service, proxy, results, otfile, output));
    }/* ww w  .j a v  a  2s .  c o  m*/
    pool.shutdown();

    while (results.size() < howManyUrls) {
        System.out.println("already processed " + results.size() + " subject links");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("crawlAll error", e);
        }

    }

    resultToFile(output, otfile);
    System.out.println("already processed " + results.size() + " subject links");

}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPAAnySearchDAO.java

@Override
protected int doCount(final Set<String> adminRealms, final SearchCond cond, final AnyTypeKind kind) {
    List<Object> parameters = Collections.synchronizedList(new ArrayList<>());

    SearchSupport svs = new SearchSupport(kind);

    Pair<String, Set<String>> filter = getAdminRealmsFilter(adminRealms, svs, parameters);

    // 1. get the query string from the search condition
    StringBuilder queryString = getQuery(buildEffectiveCond(cond, filter.getRight()), parameters, svs);

    // 2. take into account administrative realms
    queryString.insert(0, "SELECT u.any_id FROM (");
    queryString.append(") u WHERE ").append(filter.getLeft());

    // 3. prepare the COUNT query
    queryString.insert(0, "SELECT COUNT(any_id) FROM (");
    queryString.append(") count_any_id");

    Query countQuery = entityManager().createNativeQuery(queryString.toString());
    fillWithParameters(countQuery, parameters);

    return ((Number) countQuery.getSingleResult()).intValue();
}

From source file:org.opennms.ng.services.collectd.Collectd.java

/**
 * Constructor.
 */
public Collectd() {

    m_collectableServices = Collections.synchronizedList(new LinkedList<CollectableService>());
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Before
@SuppressWarnings("unchecked")
public void setup() {
    responseBuffer = new Disruptor<ResponseEvent>(new EventFactory<ResponseEvent>() {
        @Override//w  w w .j  ava  2 s .c  o m
        public ResponseEvent newInstance() {
            return new ResponseEvent();
        }
    }, 1024, Executors.newCachedThreadPool());

    firedEvents = Collections.synchronizedList(new ArrayList<CouchbaseMessage>());
    latch = new CountDownLatch(1);
    responseBuffer.handleEventsWith(new EventHandler<ResponseEvent>() {
        @Override
        public void onEvent(ResponseEvent event, long sequence, boolean endOfBatch) throws Exception {
            firedEvents.add(event.getMessage());
            latch.countDown();
        }
    });
    responseRingBuffer = responseBuffer.start();

    CoreEnvironment environment = mock(CoreEnvironment.class);
    when(environment.scheduler()).thenReturn(Schedulers.computation());
    when(environment.queryEnabled()).thenReturn(Boolean.TRUE);
    when(environment.maxRequestLifetime()).thenReturn(10000L);
    when(environment.autoreleaseAfter()).thenReturn(2000L);
    endpoint = mock(AbstractEndpoint.class);
    when(endpoint.environment()).thenReturn(environment);
    when(environment.userAgent()).thenReturn("Couchbase Client Mock");

    queue = new ArrayDeque<QueryRequest>();
    handler = new QueryHandler(endpoint, responseRingBuffer, queue, false);
    channel = new EmbeddedChannel(handler);
}

From source file:org.alfresco.repo.domain.locale.LocaleDAOTest.java

/**
 * Forces a bunch of threads to attempt Locale creation.
 */// w ww  .j  a  v  a  2  s.  c o  m
public void testConcurrentLocale() throws Throwable {
    final Locale locale = Locale.SIMPLIFIED_CHINESE;

    int threadCount = 50;
    final CountDownLatch readyLatch = new CountDownLatch(threadCount);
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch doneLatch = new CountDownLatch(threadCount);
    final List<Throwable> errors = Collections.synchronizedList(new ArrayList<Throwable>(0));
    final RetryingTransactionCallback<Long> callback = new RetryingTransactionCallback<Long>() {
        public Long execute() throws Throwable {
            String threadName = Thread.currentThread().getName();

            // Notify that we are ready
            logger.debug("Thread " + threadName + " is READY");
            readyLatch.countDown();
            // Wait for start signal
            startLatch.await();
            logger.debug("Thread " + threadName + " is GO");
            // Go
            Pair<Long, Locale> localePair = null;
            try {
                // This could fail with concurrency, but that's what we're testing
                logger.debug("Thread " + threadName + " is CREATING " + locale);
                localePair = localeDAO.getOrCreateLocalePair(locale);
            } catch (Throwable e) {
                logger.debug("Failed to create LocaleEntity.  Might retry.", e);
                throw e;
            }
            // Notify the counter that this thread is done
            logger.debug("Thread " + threadName + " is DONE");
            doneLatch.countDown();
            // Done
            return localePair.getFirst();
        }
    };
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                txnHelper.doInTransaction(callback);
            } catch (Throwable e) {
                logger.error("Error escaped from retry", e);
                errors.add(e);
            }
        }
    };
    // Fire a bunch of threads off
    for (int i = 0; i < threadCount; i++) {
        Thread thread = new Thread(runnable, getName() + "-" + i);
        thread.setDaemon(true); // Just in case there are complications
        thread.start();
    }
    // Wait for threads to be ready
    readyLatch.await(5, TimeUnit.SECONDS);
    // Let the threads go
    startLatch.countDown();
    // Wait for them all to be done (within limit of 10 seconds per thread)
    if (doneLatch.await(threadCount * 10, TimeUnit.SECONDS)) {
        logger.warn("Still waiting for threads to finish after " + threadCount + " seconds.");
    }
    // Check if there are errors
    if (errors.size() > 0) {
        throw errors.get(0);
    }
}