Java Code Examples for java.util.Collections.synchronizedList()

The following are Jave code examples for showing how to use synchronizedList() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: LightSIP   File: SipStackImpl.java   View Source Code Vote up 6 votes
public void stop() {
	if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG)) {
		logger.logDebug("stopStack -- stoppping the stack");
		logger.logStackTrace();
	}
	this.stopStack();
	if(super.sipMessageValve != null) 
		super.sipMessageValve.destroy();
	if(super.sipEventInterceptor != null) 
		super.sipEventInterceptor.destroy();
	this.sipProviders = Collections.synchronizedList(new LinkedList<SipProviderImpl>());
	this.listeningPoints = new Hashtable<String, ListeningPointImpl>();
	/*
	 * Check for presence of an event scanner ( may happen if stack is
	 * stopped before listener is attached ).
	 */
	if (this.eventScanner != null)
		this.eventScanner.forceStop();
	this.eventScanner = null;
	PostParseExecutorServices.shutdownThreadpool();

}
 
Example 2
Project: openjdk-jdk10   File: SubList.java   View Source Code Vote up 6 votes
/**
 * Lists that don't allow resizing, but allow setting values
 */
@DataProvider
public static Object[][] unresizable() {
    final List<Integer> c1 = Arrays.asList(42);
    final List<Integer> c9 = Arrays.asList(40, 41, 42, 43, 44, 45, -1,
            Integer.MIN_VALUE, 1000500);

    Object[][] l1 = unsettable();
    Object[][] l2 = {
        {c1, 0, 1},
        {c1.subList(0, 1), 0, 1},
        {Collections.checkedList(c1, Integer.class), 0, 1},
        {Collections.synchronizedList(c1), 0, 1},
        {c9, 0, 4},
        {c9, 4, 6},
        {c9.subList(1, 8), 1, 4},
        {c9.subList(1, 8), 0, 7},
        {Collections.checkedList(c9, Integer.class), 3, 6},
        {Collections.synchronizedList(c9), 3, 5},
    };
    Object[][] res = Arrays.copyOf(l1, l1.length + l2.length);
    System.arraycopy(l2, 0, res, l1.length, l2.length);
    return res;
}
 
Example 3
Project: openjdk-jdk10   File: EventRequestManagerImpl.java   View Source Code Vote up 6 votes
/**
 * Constructor.
 */
EventRequestManagerImpl(VirtualMachine vm) {
    super(vm);
    java.lang.reflect.Field[] ekinds =
        JDWP.EventKind.class.getDeclaredFields();
    int highest = 0;
    for (int i = 0; i < ekinds.length; ++i) {
        int val;
        try {
            val = ekinds[i].getInt(null);
        } catch (IllegalAccessException exc) {
            throw new RuntimeException("Got: " + exc);
        }
        if (val > highest) {
            highest = val;
        }
    }
    requestLists = new List[highest+1];
    for (int i=0; i <= highest; i++) {
        requestLists[i] = Collections.synchronizedList(new ArrayList<>());
    }
}
 
Example 4
Project: LightSIP   File: SipStackImpl.java   View Source Code Vote up 6 votes
/**
 * ReInitialize the stack instance.
 */
private void reInitialize() {
	super.reInit();
	this.eventScanner = new EventScanner(this);
	this.listeningPoints = new Hashtable<String, ListeningPointImpl>();
	this.sipProviders = Collections.synchronizedList(new LinkedList<SipProviderImpl>());
	this.sipListener = null;
	if(!getTimer().isStarted()) {			
		String defaultTimerName = configurationProperties.getProperty("gov.nist.javax.sip.TIMER_CLASS_NAME",DefaultSipTimer.class.getName());
		try {				
			setTimer((SipTimer)Class.forName(defaultTimerName).newInstance());
			getTimer().start(this, configurationProperties);
			if (getThreadAuditor().isEnabled()) {
	            // Start monitoring the timer thread
	            getTimer().schedule(new PingTimer(null), 0);
	        }
		} catch (Exception e) {
			logger
				.logError(
						"Bad configuration value for gov.nist.javax.sip.TIMER_CLASS_NAME", e);			
		}
	}
}
 
Example 5
Project: openjdk-jdk10   File: ForEachOpTest.java   View Source Code Vote up 6 votes
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testForEach(String name, TestData.OfRef<Integer> data) {
    Function<Stream<Integer>, List<Integer>> terminalFunc = s -> {
        List<Integer> l = Collections.synchronizedList(new ArrayList<>());
        s.forEach(l::add);
        return l;
    };

    // Test head
    withData(data).
            terminal(terminalFunc).
            resultAsserter(resultAsserter()).
            exercise();

    // Test multiple stages
    withData(data).
            terminal(s -> s.map(LambdaTestHelpers.identity()), terminalFunc).
            resultAsserter(resultAsserter()).
            exercise();
}
 
Example 6
Project: whackpad   File: SwingGui.java   View Source Code Vote up 5 votes
/**
 * Creates a new MyTableModel.
 */
public MyTableModel(SwingGui debugGui) {
    this.debugGui = debugGui;
    expressions = Collections.synchronizedList(new ArrayList<String>());
    values = Collections.synchronizedList(new ArrayList<String>());
    expressions.add("");
    values.add("");
}
 
Example 7
Project: Lagerta   File: ParallelCommitStrategyUnitTest.java   View Source Code Vote up 5 votes
@Test(dataProvider = TEST)
public void testCommit(
        List<List<Object>> changes,
        long deadTransaction,
        List<Integer> expectedCommitted,
        List<Map.Entry<Integer, Integer>> expectedBefore
) {
    ByteBuffer buffer = ByteBuffer.allocate(0);

    List<Long> txIdsToCommit = LongStream.range(0, changes.size()).boxed().collect(toList());
    Map<Long, TransactionData> input = new HashMap<>(changes.size());
    for (int i = 0; i < changes.size(); i++) {

        List<Map.Entry<String, List>> list = singletonList(pair(CACHE_NAME, changes.get(i)));
        TransactionData data = new TransactionData(new TransactionScope((long) i, list), buffer, new TopicPartition("topic", 0), 0L);
        input.put((long) i, data);
    }

    CommitServitor servitor = mock(CommitServitor.class);
    List<Long> actual = Collections.synchronizedList(new ArrayList<>());
    doAnswer(mock -> !mock.getArguments()[0].equals(deadTransaction) && actual.add((Long) mock.getArguments()[0]))
            .when(servitor)
            .commit(anyLong(), anyMap());

    ParallelCommitStrategy strategy = new ParallelCommitStrategy(servitor, "localGridName");
    List<Long> actualCommitted = strategy.commit(txIdsToCommit, input);

    Assert.assertEquals(actualCommitted, expectedCommitted.stream().map(Integer::longValue).collect(toList()));

    checkOrder(expectedBefore, actual);
}
 
Example 8
Project: monarch   File: JCAManagedConnection.java   View Source Code Vote up 5 votes
public JCAManagedConnection(JCAManagedConnectionFactory fact) {
  this.factory = fact;
  this.listeners = Collections
      .<ConnectionEventListener>synchronizedList(new ArrayList<ConnectionEventListener>());
  this.localTran = new JCALocalTransaction();
  this.connections =
      Collections.<GFConnectionImpl>synchronizedSet(new HashSet<GFConnectionImpl>());
}
 
Example 9
Project: hollow-reference-implementation   File: DynamoDBAnnouncementWatcher.java   View Source Code Vote up 5 votes
public DynamoDBAnnouncementWatcher(AWSCredentials credentials, String tableName, String blobNamespace) {
    this.dynamoDB = new DynamoDB(new AmazonDynamoDBClient(credentials));
    this.tableName = tableName;
    this.blobNamespace = blobNamespace;
    this.subscribedConsumers = Collections.synchronizedList(new ArrayList<HollowConsumer>());
    
    this.latestVersion = readLatestVersion();
    
    setupPollingThread();
}
 
Example 10
Project: dcs-sdk-java   File: ScreenDeviceModule.java   View Source Code Vote up 5 votes
public ScreenDeviceModule(IWebView webView, IMessageSender messageSender) {
    super(ApiConstants.NAMESPACE, messageSender);
    this.webView = webView;
    webView.addWebViewListener(new IWebView.IWebViewListener() {
        @Override
        public void onLinkClicked(String url) {
            sendLinkClickedEvent(url);
        }
    });
    this.listeners = Collections.synchronizedList(new ArrayList<IRenderVoiceInputTextListener>());
    renderListeners = new ArrayList<>();
}
 
Example 11
Project: dcs-sdk-java   File: WakeUpImpl.java   View Source Code Vote up 5 votes
public WakeUpImpl(Context context, LinkedBlockingDeque<byte[]> linkedBlockingDeque) {
    this.linkedBlockingDeque = linkedBlockingDeque;
    this.context = context.getApplicationContext();
    this.wakeUpNative = new WakeUpNative();
    this.wakeUpListeners = Collections.synchronizedList(new LinkedList<IWakeUpListener>());
    this.initWakeUp();
}
 
Example 12
Project: azure-documentdb-rxjava   File: DocumentQueryAsyncAPITest.java   View Source Code Vote up 4 votes
@Test
public void testQueryDocuments_filterFetchedResults() throws Exception {
    // queries for documents and filter out the fetched results

    int requestPageSize = 3;
    FeedOptions options = new FeedOptions();
    options.setPageSize(requestPageSize);

    Func1<Document, Boolean> isPrimeNumber = new Func1<Document, Boolean>() {

        @Override
        public Boolean call(Document doc) {
            int n = doc.getInt("counter");
            if (n <= 1) return false;
            for(int i = 2; 2*i < n; i++) {
                if(n % i == 0)
                    return false;
            }
            return true;
        }
    };
    
    List<Document> resultList = Collections.synchronizedList(new ArrayList<Document>());
    
    asyncClient
        .queryDocuments(createdCollection.getSelfLink(), "SELECT * FROM root", options)
        .map(FeedResponsePage::getResults)              // map the page to the list of documents
        .concatMap(Observable::from)                    // flatten the observable<list<document>> to observable<document>
        .filter(isPrimeNumber)                          // filter documents using isPrimeNumber predicate
        .subscribe(doc -> resultList.add(doc));         // collect the results
    
    Thread.sleep(4000);
    
    int expectedNumberOfPrimes = 0;
    // find all the documents with prime number counter
    for(int i = 0; i < numberOfDocuments; i++) {
        boolean isPrime = true;
        if (i <= 1) isPrime = false;
        for(int j = 2; 2*j < i; j++) {
            if(i % j == 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime) {
            expectedNumberOfPrimes++;
        }
    }
    
    // assert that we only collected what's expected
    assertThat(resultList, hasSize(expectedNumberOfPrimes));
}
 
Example 13
Project: iot-edge-greengrass   File: Sensor1.java   View Source Code Vote up 4 votes
/**
 * Periodically publish the lastN on a stream.
 * @param stream tuples to 
 * @param count sliding window size "lastN"
 * @param nSec publish frequency
 * @param event sensor's publish event label
 */
private void periodicallyPublishLastNInfo(TStream<JsonObject> stream, 
        int count, int nSec, String event) {

    // Demonstrate periodic publishing of a sliding window if
    // something changed since it was last published.

    // Maintain a sliding window of the last N tuples.
    // TODO today, windows don't provide "anytime" access to their collection
    // so maintain our own current copy of the collection that we can
    // access it when needed.
    // 
    List<JsonObject> lastN = Collections.synchronizedList(new ArrayList<>());
    stream.last(count, JsonTuples.keyFn())
        .aggregate((samples, key) -> samples)
        .tag(event+".lastN")
        .sink(samples -> {
                // Capture the new list/window.  
                synchronized(lastN) {
                    lastN.clear();
                    lastN.addAll(samples);
                }
            });

    // Publish the lastN (with trimmed down info) every nSec seconds
    // if anything changed since the last publish.
    TStream<JsonObject> periodicLastN = 
            t.poll(() -> 1, nSec, TimeUnit.SECONDS).tag(event+".trigger")
            .filter(trigger -> !lastN.isEmpty()).tag(event+".changed")
            .map(trigger -> {
                synchronized(lastN) {
                    // create a single JsonObject with the list
                    // of reduced-content samples
                    JsonObject jo = new JsonObject();
                    jo.addProperty(KEY_ID, sensorId);
                    jo.addProperty(KEY_TS, System.currentTimeMillis());
                    jo.addProperty("window", count);
                    jo.addProperty("pubFreqSec", nSec);
                    JsonArray ja = new JsonArray();
                    jo.add("lastN", ja);
                    for (JsonObject j : lastN) {
                        JsonObject jo2 = new JsonObject();
                        ja.add(jo2);
                        jo2.add(KEY_TS, j.get(KEY_TS));
                        // reduce size: include only 2 significant digits
                        jo2.addProperty(KEY_READING, String.format("%.2f", 
                            JsonTuples.getStatistic(j, MEAN).getAsDouble()));
                    }
                    lastN.clear();
                    return jo;
                }
            })
            .tag(event);

    traceStream(periodicLastN, event);

    // Use a pressureReliever to prevent backpressure if the broker
    // can't be contacted.
    // TODO enhance MqttDevice with configurable reliever. 
    app.mqttDevice().events(
            PlumbingStreams.pressureReliever(periodicLastN, tuple -> 0, 30)
                .tag(event+".pressureRelieved"),
            app.sensorEventId(sensorId, event), QoS.FIRE_AND_FORGET);
}
 
Example 14
Project: iTAP-controller   File: OFConnection.java   View Source Code Vote up 4 votes
@Override
public <REPLY extends OFStatsReply> ListenableFuture<List<REPLY>> writeStatsRequest(
        OFStatsRequest<REPLY> request) {
    if (!isConnected())
        return Futures.immediateFailedFuture(new SwitchDisconnectedException(getDatapathId()));

    final DeliverableListenableFuture<List<REPLY>> future =
            new DeliverableListenableFuture<List<REPLY>>();

    Deliverable<REPLY> deliverable = new Deliverable<REPLY>() {
        private final List<REPLY> results = Collections
                .synchronizedList(new ArrayList<REPLY>());

        @Override
        public void deliver(REPLY reply) {
            results.add(reply);
            if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
                // done
                future.deliver(results);
            }
        }

        @Override
        public void deliverError(Throwable cause) {
            future.deliverError(cause);
        }

        @Override
        public boolean isDone() {
            return future.isDone();
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }
    };

    registerDeliverable(request.getXid(), deliverable);
    this.write(request);
    return future;
}
 
Example 15
Project: sponge   File: DecomposedQueue.java   View Source Code Vote up 4 votes
public DecomposedQueue(int capacity, boolean allowConcurrentEventTypeProcessing) {
    this.capacity = capacity;
    this.allowConcurrentEventTypeProcessing = allowConcurrentEventTypeProcessing;

    entries = Collections.synchronizedList(new ArrayList<>(capacity));
}
 
Example 16
Project: visuflow-plugin   File: JimpleBreakpointManager.java   View Source Code Vote up 4 votes
private JimpleBreakpointManager() {
	breakpoints = Collections.synchronizedList(new ArrayList<>());
	ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
	registerAtEventHandler();
}
 
Example 17
Project: fresco_floodlight   File: OFConnection.java   View Source Code Vote up 4 votes
@Override
public <REPLY extends OFStatsReply> ListenableFuture<List<REPLY>> writeStatsRequest(
		OFStatsRequest<REPLY> request) {
	if (!isConnected()) {
		return Futures.immediateFailedFuture(new SwitchDisconnectedException(getDatapathId()));
	}

	final DeliverableListenableFuture<List<REPLY>> future =
			new DeliverableListenableFuture<List<REPLY>>();

	Deliverable<REPLY> deliverable = new Deliverable<REPLY>() {
		private final List<REPLY> results = Collections
				.synchronizedList(new ArrayList<REPLY>());

		@Override
		public void deliver(REPLY reply) {
			results.add(reply);
			if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
				// done
				future.deliver(results);
			}
		}

		@Override
		public void deliverError(Throwable cause) {
			future.deliverError(cause);
		}

		@Override
		public boolean isDone() {
			return future.isDone();
		}

		@Override
		public boolean cancel(boolean mayInterruptIfRunning) {
			return future.cancel(mayInterruptIfRunning);
		}
	};

	registerDeliverable(request.getXid(), deliverable);
	this.write(request);
	return future;
}
 
Example 18
Project: JZAndroidChart   File: ScatterDataSet.java   View Source Code Vote up 4 votes
public void addTextValueRenderer(TextValueRenderer textValueRenderer) {
  if (mTextValueRenderers == null) {
    mTextValueRenderers = Collections.synchronizedList(new ArrayList<TextValueRenderer>());
  }
  this.mTextValueRenderers.add(textValueRenderer);
}
 
Example 19
Project: aos-MediaLib   File: XmlDb.java   View Source Code Vote up 4 votes
private XmlDb(){
    System.setProperty("org.xml.sax.driver", "org.xmlpull.v1.sax2.Driver");
    mResumeChangeListener = new ArrayList<>();
    mOnParseListeners = Collections.synchronizedList(new ArrayList<ParseListener>());
}
 
Example 20
Project: NBANDROID-V2   File: LogTableModel.java   View Source Code Vote up 4 votes
public LogTableModel(LogFilter filter) {
    this.data = Collections.synchronizedList(new ArrayList<LogEvent>());
    this.filter = filter;
}