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:com.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java

@Test
public void testSimple() throws Exception {
    Timing timing = new Timing();
    DistributedQueue<String> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {/*from  w w w .  java 2 s .  c om*/
        client.start();

        final List<String> messages = new CopyOnWriteArrayList<String>();
        final CountDownLatch latch = new CountDownLatch(2);
        final Semaphore semaphore = new Semaphore(0);
        QueueConsumer<String> consumer = new QueueConsumer<String>() {
            @Override
            public void consumeMessage(String message) throws Exception {
                messages.add(message);
                semaphore.acquire();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        queue = QueueBuilder.builder(client, consumer, serializer, "/queue")
                .executor(Executors.newSingleThreadExecutor()).maxItems(1).buildQueue();
        queue.start();

        QueuePutListener<String> listener = new QueuePutListener<String>() {
            @Override
            public void putCompleted(String item) {
                latch.countDown();
            }

            @Override
            public void putMultiCompleted(MultiItem<String> items) {
            }
        };
        queue.getPutListenerContainer().addListener(listener);

        Assert.assertTrue(queue.put("1", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should end up in consumer
        Assert.assertTrue(queue.put("2", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should sit blocking in DistributedQueue
        Assert.assertTrue(timing.awaitLatch(latch));
        timing.sleepABit();
        Assert.assertFalse(queue.put("3", timing.multiple(.5).milliseconds(), TimeUnit.MILLISECONDS));

        semaphore.release(100);
        Assert.assertTrue(queue.put("3", timing.milliseconds(), TimeUnit.MILLISECONDS));
        Assert.assertTrue(queue.put("4", timing.milliseconds(), TimeUnit.MILLISECONDS));
        Assert.assertTrue(queue.put("5", timing.milliseconds(), TimeUnit.MILLISECONDS));

        for (int i = 0; i < 5; ++i) {
            if (messages.size() == 3) {
                break;
            }
            timing.sleepABit();
        }
        timing.sleepABit();

        Assert.assertEquals(messages, Arrays.asList("1", "2", "3", "4", "5"));
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.devbrackets.android.exomedia.core.exoplayer.EMExoPlayer.java

public EMExoPlayer(@Nullable RenderBuilder rendererBuilder) {
    bufferRepeater.setRepeaterDelay(BUFFER_REPEAT_DELAY);
    bufferRepeater.setRepeatListener(new BufferRepeatListener());

    player = ExoPlayer.Factory.newInstance(RENDER_COUNT, BUFFER_LENGTH_MIN, REBUFFER_LENGTH_MIN);
    player.addListener(this);

    mainHandler = new Handler();
    listeners = new CopyOnWriteArrayList<>();
    rendererBuildingState = RenderBuildingState.IDLE;
    player.setSelectedTrack(RENDER_CLOSED_CAPTION, DISABLED_TRACK);

    replaceRenderBuilder(rendererBuilder);
}

From source file:org.elasticsearch.client.RestClientMultipleHostsIntegTests.java

public void testAsyncRequests() throws Exception {
    int numRequests = randomIntBetween(5, 20);
    final CountDownLatch latch = new CountDownLatch(numRequests);
    final List<TestResponse> responses = new CopyOnWriteArrayList<>();
    for (int i = 0; i < numRequests; i++) {
        final String method = RestClientTestUtil.randomHttpMethod(getRandom());
        //we don't test status codes that are subject to retries as they interfere with hosts being stopped
        final int statusCode = randomBoolean() ? randomOkStatusCode(getRandom())
                : randomErrorNoRetryStatusCode(getRandom());
        restClient.performRequestAsync(method, "/" + statusCode, new ResponseListener() {
            @Override//  ww w.  j ava2 s  .c o m
            public void onSuccess(Response response) {
                responses.add(new TestResponse(method, statusCode, response));
                latch.countDown();
            }

            @Override
            public void onFailure(Exception exception) {
                responses.add(new TestResponse(method, statusCode, exception));
                latch.countDown();
            }
        });
    }
    assertTrue(latch.await(5, TimeUnit.SECONDS));

    assertEquals(numRequests, responses.size());
    for (TestResponse testResponse : responses) {
        Response response = testResponse.getResponse();
        assertEquals(testResponse.method, response.getRequestLine().getMethod());
        assertEquals(testResponse.statusCode, response.getStatusLine().getStatusCode());
        assertEquals((pathPrefix.length() > 0 ? pathPrefix : "") + "/" + testResponse.statusCode,
                response.getRequestLine().getUri());
    }
}

From source file:de.static_interface.sinklibrary.SinkLibrary.java

@Override
public void onEnable() {

    getLogger().info("Loading...");
    commands = new ConcurrentHashMap<>();
    commandAliases = new ConcurrentHashMap<>();
    loadedLibs = new CopyOnWriteArrayList<>();

    ingameUserProvider = new IngameUserProvider();
    consoleUserProvider = new ConsoleUserProvider();
    ircUserProvider = new IrcUserProvider();

    registerUserImplementation(ConsoleCommandSender.class, consoleUserProvider);
    registerUserImplementation(User.class, ircUserProvider);
    registerUserImplementation(Player.class, ingameUserProvider);
    registerUserImplementation(FakeSender.class, new FakeUserProvider());

    LIB_FOLDER = new File(getCustomDataFolder(), "libs");

    if ((!LIB_FOLDER.exists() && !LIB_FOLDER.mkdirs())) {
        getLogger().warning("Coudln't create lib directory");
    }/* w  w  w .  java2s  .c  o m*/

    LanguageConfiguration languageConfiguration = new LanguageConfiguration();
    languageConfiguration.init();

    // Check optional dependencies
    if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
        getLogger().warning("Vault Plugin not found. Disabling economy and some permission features.");
        permissionsAvailable = false;
        economyAvailable = false;
        chatAvailable = false;
        vaultAvailable = false;
    } else {
        vaultAvailable = true;

        if (!setupChat()) {
            getLogger().warning("Chat providing plugin not found. Disabling chat features.");
            chatAvailable = false;
        }

        if (!setupEcononmy()) {
            getLogger().warning("Economy Plugin not found. Disabling economy features.");
            economyAvailable = false;
        }
        if (!setupPermissions()) {
            getLogger().warning("Permissions Plugin not found. Disabling permissions features.");
            permissionsAvailable = false;
        }
    }

    if (!getCustomDataFolder().exists()) {
        try {
            boolean success = getCustomDataFolder().mkdirs();
            if (!success) {
                throw new IOException("Couldn't create directories!");
            }
        } catch (Exception e) {
            Bukkit.getLogger().log(Level.SEVERE, "Couldn't create Data Folder!", e); // Log via Bukkits Logger, because Log File doesnt exists
        }
    }

    if (chatAvailable && economyAvailable && permissionsAvailable) {
        getLogger().info("Successfully hooked into permissions, economy and chat.");
    }

    // Register Listeners and Commands
    registerListeners();
    registerCommands();

    Bukkit.getScheduler().scheduleSyncRepeatingTask(this, getSinkTimer(), 1000, 50);

    // Check for updates
    update();

    // Init players (reload etc)
    for (Player p : BukkitUtil.getOnlinePlayers()) {
        onRefreshDisplayName(p);
    }

    Bukkit.getPluginManager().registerEvents(new IrcCommandListener(), this);

    if (!isSinkChatAvailable()) {
        Bukkit.getPluginManager().registerEvents(new IrcLinkListener(), this);
    }

    loadLibs(getConsoleUser());
}

From source file:org.carbondata.processing.store.writer.AbstractFactDataWriter.java

public AbstractFactDataWriter(String storeLocation, int measureCount, int mdKeyLength, String tableName,
        boolean isNodeHolder, IFileManagerComposite fileManager, int[] keyBlockSize, boolean isUpdateFact,
        CarbonDataFileAttributes carbonDataFileAttributes, List<ColumnSchema> columnSchema) {

    // measure count
    this.measureCount = measureCount;
    // table name
    this.tableName = tableName;

    this.storeLocation = storeLocation;
    this.blockletInfoList = new ArrayList<BlockletInfoColumnar>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
    // get max file size;
    CarbonProperties propInstance = CarbonProperties.getInstance();
    this.fileSizeInBytes = Long
            .parseLong(propInstance.getProperty(CarbonCommonConstants.MAX_FILE_SIZE,
                    CarbonCommonConstants.MAX_FILE_SIZE_DEFAULT_VAL))
            * CarbonCommonConstants.BYTE_TO_KB_CONVERSION_FACTOR
            * CarbonCommonConstants.BYTE_TO_KB_CONVERSION_FACTOR * 1L;
    this.spaceReservedForBlockMetaSize = Integer
            .parseInt(propInstance.getProperty(CarbonCommonConstants.CARBON_BLOCK_META_RESERVED_SPACE,
                    CarbonCommonConstants.CARBON_BLOCK_META_RESERVED_SPACE_DEFAULT));
    this.dataBlockSize = fileSizeInBytes - (fileSizeInBytes * spaceReservedForBlockMetaSize) / 100;
    LOGGER.info("Total file size: " + fileSizeInBytes + " and dataBlock Size: " + dataBlockSize);
    this.isNodeHolderRequired = Boolean
            .valueOf(CarbonCommonConstants.WRITE_ALL_NODE_IN_SINGLE_TIME_DEFAULT_VALUE);
    this.fileManager = fileManager;

    /**//  w  ww .  j  a  v a  2s.  c o m
     * keyBlockSize
     */
    this.keyBlockSize = keyBlockSize;
    /**
     *
     */
    this.mdkeySize = mdKeyLength;

    this.isNodeHolderRequired = this.isNodeHolderRequired && isNodeHolder;
    if (this.isNodeHolderRequired) {
        this.nodeHolderList = new CopyOnWriteArrayList<NodeHolder>();

        this.executorService = Executors.newFixedThreadPool(5);
    }

    //TODO: We should delete the levelmetadata file after reading here.
    this.localCardinality = CarbonMergerUtil.getCardinalityFromLevelMetadata(storeLocation, tableName);
    this.carbonDataFileAttributes = carbonDataFileAttributes;
    CarbonTableIdentifier tableIdentifier = new CarbonTableIdentifier(databaseName, tableName);
    carbonTablePath = CarbonStorePath.getCarbonTablePath(storeLocation, tableIdentifier);
    List<Integer> cardinalityList = new ArrayList<Integer>();
    thriftColumnSchemaList = getColumnSchemaListAndCardinality(cardinalityList, localCardinality, columnSchema);
    localCardinality = ArrayUtils.toPrimitive(cardinalityList.toArray(new Integer[cardinalityList.size()]));
}

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

@Test
public void shouldListEmptyMetricTypes() {
    // Data & mocks
    long currentTime = System.currentTimeMillis();
    when(metricsService.findMetricsWithFilters(anyString(), anyObject(), anyString()))
            .thenAnswer(invocationOnMock -> Observable.empty());

    // Test & assertions
    List<org.hawkular.inventory.api.model.MetricType.Blueprint> collected = new CopyOnWriteArrayList<>();
    InventoryHelper.listMetricTypes(metricsService, "tenant", "feed", currentTime).toList()
            .subscribe(collected::addAll, Throwables::propagate);
    Assert.assertTrue(collected.isEmpty());
}

From source file:org.jimcat.services.jobs.Job.java

/**
 * //  w  w w .j  ava 2  s .c  o m
 * This constructor creats a new job using the given fields.
 * 
 * @param manager -
 *            the jobManager used to execute this job.
 * @param name -
 *            the name of this job, e.g. Image Import
 * @param description -
 *            a short description for the job
 */
public Job(JobManager manager, String name, String description) {
    // Job values
    state = JobState.PREPARING;
    jobManager = manager;
    jobName = name;
    jobDescription = description;

    // Listener management
    listeners = new CopyOnWriteArrayList<JobListener>();

    // concurrency management
    suspendSemaphore = new Semaphore(1);
    stateLock = new Object();
    failerDescriptionLock = new Object();
}

From source file:org.ethereum.core.Block.java

public Block(byte[] parentHash, byte[] unclesHash, byte[] coinbase, byte[] logsBloom, byte[] difficulty,
        long number, byte[] gasLimit, long gasUsed, long timestamp, byte[] extraData, byte[] mixHash,
        byte[] nonce, List<Transaction> transactionsList, List<BlockHeader> uncleList, byte[] minimumGasPrice) {
    this.header = new BlockHeader(parentHash, unclesHash, coinbase, logsBloom, difficulty, number, gasLimit,
            gasUsed, timestamp, extraData, minimumGasPrice, CollectionUtils.size(uncleList));

    this.transactionsList = transactionsList;
    if (this.transactionsList == null) {
        this.transactionsList = new CopyOnWriteArrayList<>();
    }/*from  w  w w  .  java2  s. c  om*/

    this.uncleList = uncleList;
    if (this.uncleList == null) {
        this.uncleList = new CopyOnWriteArrayList<>();
    }

    this.parsed = true;
}

From source file:org.wso2.carbon.event.input.adaptor.websocket.WebsocketEventAdaptorType.java

@Override
public String subscribe(InputEventAdaptorMessageConfiguration inputEventAdaptorMessageConfiguration,
        InputEventAdaptorListener inputEventAdaptorListener,
        InputEventAdaptorConfiguration inputEventAdaptorConfiguration, AxisConfiguration axisConfiguration) {

    String subscriptionId = UUID.randomUUID().toString();

    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    String topic = inputEventAdaptorMessageConfiguration.getInputMessageProperties()
            .get(WebsocketEventAdaptorConstants.ADAPTOR_MESSAGE_TOPIC);
    String socketServerUrl = inputEventAdaptorConfiguration.getInputProperties()
            .get(WebsocketEventAdaptorConstants.ADAPTER_SERVER_URL);

    if (!socketServerUrl.startsWith("ws://")) {
        throw new InputEventAdaptorEventProcessingException(
                "Provided websocket URL " + socketServerUrl + " is invalid."); //TODO: Make this exception propagate to the UI.
    }/*from  w ww . j a v a2s  .c  o m*/

    if (topic != null) {
        socketServerUrl = socketServerUrl + "/" + topic;
    } else {
        topic = ""; //Using empty string to map the cases with no topic, because topic is optional
    }
    ConcurrentHashMap<String, ConcurrentHashMap<String, CopyOnWriteArrayList<ClientManagerWrapper>>> tenantSpecificAdaptorMap = inputEventAdaptorClientManagerMap
            .get(tenantId);
    if (tenantSpecificAdaptorMap == null) {
        tenantSpecificAdaptorMap = new ConcurrentHashMap<String, ConcurrentHashMap<String, CopyOnWriteArrayList<ClientManagerWrapper>>>();
        if (null != inputEventAdaptorClientManagerMap.putIfAbsent(tenantId, tenantSpecificAdaptorMap)) {
            tenantSpecificAdaptorMap = inputEventAdaptorClientManagerMap.get(tenantId);
        }
    }

    ConcurrentHashMap<String, CopyOnWriteArrayList<ClientManagerWrapper>> adaptorSpecificTopicMap = tenantSpecificAdaptorMap
            .get(inputEventAdaptorConfiguration.getName());

    if (adaptorSpecificTopicMap == null) {
        adaptorSpecificTopicMap = new ConcurrentHashMap<String, CopyOnWriteArrayList<ClientManagerWrapper>>();
        if (null != tenantSpecificAdaptorMap.put(inputEventAdaptorConfiguration.getName(),
                adaptorSpecificTopicMap)) {
            adaptorSpecificTopicMap = tenantSpecificAdaptorMap.get(inputEventAdaptorConfiguration.getName());
        }
    }

    CopyOnWriteArrayList<ClientManagerWrapper> topicSpecificClientManagers = adaptorSpecificTopicMap.get(topic);
    if (topicSpecificClientManagers == null) {
        topicSpecificClientManagers = new CopyOnWriteArrayList<ClientManagerWrapper>();
        if (null != adaptorSpecificTopicMap.putIfAbsent(topic, topicSpecificClientManagers)) {
            topicSpecificClientManagers = adaptorSpecificTopicMap.get(topic);
        }
    }

    ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    ClientManager client = ClientManager.createClient();
    ClientManagerWrapper clientManagerWrapper = new ClientManagerWrapper();
    clientManagerWrapper.setClientManager(client);
    clientManagerWrapper.setSubscriptionId(subscriptionId);
    try {
        client.connectToServer(new WebsocketClient(inputEventAdaptorListener), clientEndpointConfig,
                new URI(socketServerUrl)); //TODO: Handle reconnecting, in case server disconnects. Suggestion: Create a scheduler.
        topicSpecificClientManagers.add(clientManagerWrapper);
    } catch (DeploymentException e) {
        throw new InputEventAdaptorEventProcessingException(e); //TODO: These exceptions might get modified into new types, as these do not propagate to the UI.
    } catch (IOException e) {
        throw new InputEventAdaptorEventProcessingException(e);
    } catch (Throwable e) {
        throw new InputEventAdaptorEventProcessingException(e);
    }
    return subscriptionId;
}

From source file:org.apache.archiva.web.api.DefaultFileUploadService.java

/**
 * FIXME must be per session synchronized not globally
 *
 * @return/*from w  ww. ja  v a  2s  .c  om*/
 */
protected synchronized List<FileMetadata> getSessionFilesList() {
    List<FileMetadata> fileMetadatas = (List<FileMetadata>) httpServletRequest.getSession()
            .getAttribute(FILES_SESSION_KEY);
    if (fileMetadatas == null) {
        fileMetadatas = new CopyOnWriteArrayList<>();
        httpServletRequest.getSession().setAttribute(FILES_SESSION_KEY, fileMetadatas);
    }
    return fileMetadatas;
}