Example usage for java.util Collections synchronizedSet

List of usage examples for java.util Collections synchronizedSet

Introduction

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

Prototype

public static <T> Set<T> synchronizedSet(Set<T> s) 

Source Link

Document

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

Usage

From source file:org.apache.james.mailrepository.file.FileMailRepository.java

@Override
@PostConstruct/*from  www  .  jav a2  s . c  o  m*/
public void init() throws Exception {
    try {
        DefaultConfigurationBuilder reposConfiguration = new DefaultConfigurationBuilder();

        reposConfiguration.addProperty("[@destinationURL]", destination);
        objectRepository = new FilePersistentObjectRepository();
        objectRepository.setLog(getLogger());
        objectRepository.setFileSystem(fileSystem);
        objectRepository.configure(reposConfiguration);
        objectRepository.init();

        streamRepository = new FilePersistentStreamRepository();
        streamRepository.setLog(getLogger());
        streamRepository.setFileSystem(fileSystem);
        streamRepository.configure(reposConfiguration);
        streamRepository.init();

        if (cacheKeys)
            keys = Collections.synchronizedSet(new HashSet<String>());

        // Finds non-matching pairs and deletes the extra files
        HashSet<String> streamKeys = new HashSet<String>();
        for (Iterator<String> i = streamRepository.list(); i.hasNext();) {
            streamKeys.add(i.next());
        }
        HashSet<String> objectKeys = new HashSet<String>();
        for (Iterator<String> i = objectRepository.list(); i.hasNext();) {
            objectKeys.add(i.next());
        }

        @SuppressWarnings("unchecked")
        Collection<String> strandedStreams = (Collection<String>) streamKeys.clone();
        strandedStreams.removeAll(objectKeys);
        for (Object strandedStream : strandedStreams) {
            String key = (String) strandedStream;
            remove(key);
        }

        @SuppressWarnings("unchecked")
        Collection<String> strandedObjects = (Collection<String>) objectKeys.clone();
        strandedObjects.removeAll(streamKeys);
        for (Object strandedObject : strandedObjects) {
            String key = (String) strandedObject;
            remove(key);
        }

        if (keys != null) {
            // Next get a list from the object repository
            // and use that for the list of keys
            keys.clear();
            for (Iterator<String> i = objectRepository.list(); i.hasNext();) {
                keys.add(i.next());
            }
        }
        if (getLogger().isDebugEnabled()) {
            String logBuffer = getClass().getName() + " created in " + destination;
            getLogger().debug(logBuffer);
        }
    } catch (Exception e) {
        final String message = "Failed to retrieve Store component:" + e.getMessage();
        getLogger().error(message, e);
        throw e;
    }
}

From source file:org.echocat.jomon.net.cluster.channel.multicast.MulticastClusterChannelIntegrationTest.java

@Test
@Ignore("Does currently not work on not good performing test machines.")
public void test3InstancesConcurrent() throws Exception {
    final List<MulticastClusterChannel> channels = channels(U1, U2, U3);
    try {/*from www .ja  v  a 2 s. com*/
        final int numberOfWorkersPerChannel = 10;
        final int numberOfMessagesPerWorker = 1000;
        final Set<String> messagesSend = Collections.synchronizedSet(new HashSet<String>());
        final OverPeriodCounter counter = new OverPeriodCounter(new Duration("1m"), new Duration("1s"));
        final List<Worker> workers = createWorkersFor(numberOfWorkersPerChannel, numberOfMessagesPerWorker,
                messagesSend, channels, counter);
        final StopWatch stopWatch = new StopWatch();
        run(workers);

        assertThat(stopWatch.getCurrentDuration(),
                isLessThan(new Duration("2ms").multiplyBy(messagesSend.size())));
        assertThat(messagesSend,
                hasSize(channels.size() * numberOfWorkersPerChannel * numberOfMessagesPerWorker));

        waitFor(new StateCondition<MulticastClusterChannel>(
                new Duration("1ms").multiplyBy(numberOfMessagesPerWorker).multiplyBy(0.15)) {
            @Override
            public boolean check(@Nullable MulticastClusterChannel clusterChannel) throws Exception {
                for (final MulticastClusterChannel channel : channels) {
                    assertThat(channel.getSendingQueueSize(), is(0));
                }
                assertThat(getNumberOfReceivedMessages(), is(messagesSend.size() * (channels.size() - 1)));
                final Map<String, AtomicInteger> messageToCount = getMessageToCount();
                for (final String messageSend : messagesSend) {
                    final AtomicInteger count = messageToCount.get(messageSend);
                    assertThat(count, isNotNull());
                    assertThat(count.get(), is(channels.size() - 1));
                }
                return true;
            }
        });

        _logger.info("send: " + counter.getAsDouble() + " m/s, received: "
                + getNumberMessagesReceivedPerSecond() + " m/s");

    } finally {
        closeQuietly(channels);
    }
}

From source file:org.paxle.filter.webgraph.impl.GraphFilter.java

@SuppressWarnings("unchecked")
public synchronized Set<String> getRelationsMap(String domainName) {
    if (this.domainRelations.containsKey(domainName)) {
        return (Set<String>) this.domainRelations.get(domainName);
    } else {//  w w w .  j  av a 2  s  . c o m
        // creating an new map
        Set<String> domains = new HashSet<String>();
        domains = (Set<String>) Collections.synchronizedSet(domains);
        this.domainRelations.put(domainName, domains);
        return domains;
    }
}

From source file:org.apache.jmeter.protocol.jdbc.config.DataSourceElement.java

@Override
public void testStarted() {
    this.setRunningVersion(true);
    TestBeanHelper.prepare(this);
    JMeterVariables variables = getThreadContext().getVariables();
    String poolName = getDataSource();
    if (JOrphanUtils.isBlank(poolName)) {
        throw new IllegalArgumentException("Variable Name must not be empty for element:" + getName());
    } else if (variables.getObject(poolName) != null) {
        log.error("JDBC data source already defined for: " + poolName);
    } else {// w  ww  .  j ava  2s  .  c o m
        String maxPool = getPoolMax();
        perThreadPoolSet = Collections.synchronizedSet(new HashSet<BasicDataSource>());
        if (maxPool.equals("0")) { // i.e. if we want per thread pooling
            variables.putObject(poolName, new DataSourceComponentImpl()); // pool will be created later
        } else {
            BasicDataSource src = initPool(maxPool);
            synchronized (this) {
                dbcpDataSource = src;
                variables.putObject(poolName, new DataSourceComponentImpl(dbcpDataSource));
            }
        }
    }
}

From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java

private static Set<InetAddress> discoverGateways() throws InterruptedException, IOException {
    final Set<InetAddress> foundGateways = Collections.synchronizedSet(new HashSet<InetAddress>());
    Set<InetAddress> potentialGateways = NetworkUtils.getPotentialGatewayAddresses(); // port 5351

    DatagramChannel unicastChannel = null;
    try {/*from  w  w w . j av a  2 s. co m*/
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(Collections.singletonList(unicastChannel));
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                new ExternalAddressNatPmpResponse(packet); // should error out if not valid

                foundGateways.add(sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(16);
        ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest();
        eanpr.dump(outBuf);

        outBuf.flip();

        for (InetAddress potentialGateway : potentialGateways) {
            communicator.send(unicastChannel, new InetSocketAddress(potentialGateway, 5351),
                    outBuf.asReadOnlyBuffer());
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashSet<>(foundGateways);
}

From source file:com.example.com.jglx.android.app.util.video.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 * //  ww  w  .ja va  2s.  co  m
 * @param cacheParams
 *            The cache parameters to initialize the cache
 */
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {

        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                    BitmapDrawable newValue) {
                if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    // The removed entry is a recycling drawable, so notify
                    // it
                    // that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                } else {
                    // The removed entry is a standard BitmapDrawable

                    if (Utils.hasHoneycomb()) {
                        // We're running on Honeycomb or later, so add the
                        // bitmap
                        // to a SoftReference set for possible use with
                        // inBitmap later
                        mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                    }
                }
            }

            /**
             * Measure item size in kilobytes rather than units which is
             * more practical for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }

}

From source file:org.nativescript.widgets.image.Cache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *///from   ww w  .jav  a  2  s.co m
private void init(CacheParams cacheParams) {
    clearCache();
    if (mReusableBitmaps != null) {
        mReusableBitmaps.clear();
        mReusableBitmaps = null;
    }

    mParams = cacheParams;

    // Set up memory cache
    if (mParams.memoryCacheEnabled) {
        if (Worker.debuggable > 0) {
            Log.v(TAG, "Memory cache created (size = " + mParams.memCacheSize + ")");
        }

        // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
        // of SoftReferences which will actually not be very effective due to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better approach
        // would be to use a strongly references bitmaps, however this would require some
        // balancing of memory usage between this set and the bitmap LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size would just need to
        // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCacheUsage = new HashMap<String, Integer>();
        mMemoryCache = new LruCache<String, Bitmap>(mParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
                Integer count = mMemoryCacheUsage.get(key);
                if (Utils.hasHoneycomb() && (count == null || count == 0)) {
                    // We're running on Honeycomb or later, so add the bitmap
                    // to a SoftReference set for possible use with inBitmap later
                    mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue));
                }
            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, Bitmap value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }
}

From source file:libepg.ts.packet.PROGRAM_ID.java

private PROGRAM_ID(String pidName, Integer pid, Integer... pids) {

    this.pidName = pidName;
    if ((this.pidName == null) || ("".equals(this.pidName))) {
        throw new IllegalArgumentException("???????????");
    }// ww  w  .  j  a va 2s  .c o  m

    List<Integer> t = new ArrayList<>();
    if (pid != null) {
        t.add(pid);
    } else {
        throw new NullPointerException("PID??????");
    }
    if (pids != null) {
        t.addAll(Arrays.asList(pids));
    }
    Range<Integer> r = Range.between(0x0000, 0x1FFF);
    for (Integer i : t) {
        if (!r.contains(i)) {
            MessageFormat msg = new MessageFormat("PID????PID={0}");
            Object[] parameters = { Integer.toHexString(i) };
            throw new IllegalArgumentException(msg.format(parameters));
        }
    }
    Set<Integer> temp = Collections.synchronizedSet(new HashSet<Integer>());
    temp.addAll(t);
    this.pids = Collections.unmodifiableSet(temp);
}

From source file:mitm.djigzo.web.pages.Users.java

@SetupRender
public void setupRender() {
    if (selected == null) {
        selected = Collections.synchronizedSet(new HashSet<String>());
    } else {/*ww w .jav a  2 s . c  o  m*/
        selected.clear();
    }

    /*
     * set initial sorting if sorting is not yet set
     */
    if (grid.getSortModel().getColumnSort(EMAIL_COLUMN) == ColumnSort.UNSORTED) {
        grid.getSortModel().updateSort(EMAIL_COLUMN);
    }
}

From source file:org.echocat.jomon.net.cluster.channel.tcp.TcpClusterChannelIntegrationTest.java

@Test
public void test6InstancesConcurrent() throws Exception {
    final List<TcpClusterChannel> channels = channels(U1, U2, U3, U4, U5, U6);
    try {/*from w  ww .  j av a  2s .  com*/
        final int numberOfWorkersPerChannel = 5;
        final int numberOfMessagesPerWorker = 100;
        final Set<String> messagesSend = Collections.synchronizedSet(new HashSet<String>());
        final OverPeriodCounter counter = new OverPeriodCounter(new Duration("1m"), new Duration("1s"));
        final List<Worker> workers = createWorkersFor(numberOfWorkersPerChannel, numberOfMessagesPerWorker,
                messagesSend, channels, counter);
        final StopWatch stopWatch = new StopWatch();
        run(workers);

        assertThat(stopWatch.getCurrentDuration(),
                isLessThan(new Duration("2ms").multiplyBy(messagesSend.size())));
        assertThat(messagesSend,
                hasSize(channels.size() * numberOfWorkersPerChannel * numberOfMessagesPerWorker));

        waitFor(new StateCondition<TcpClusterChannel>(
                new Duration("3ms").multiplyBy(numberOfMessagesPerWorker)) {
            @Override
            public boolean check(@Nullable TcpClusterChannel clusterChannel) throws Exception {
                assertThat(getNumberOfReceivedMessages(), is(messagesSend.size() * (channels.size() - 1)));
                final Map<String, AtomicInteger> messageToCount = getMessageToCount();
                for (final String messageSend : messagesSend) {
                    final AtomicInteger count = messageToCount.get(messageSend);
                    assertThat(count, isNotNull());
                    assertThat(count.get(), is(channels.size() - 1));
                }
                return true;
            }
        });

        for (final TcpClusterChannel channel : channels) {
            _logger.info("Nodes status of (" + channel + "):\n" + formatNodesStatusOf(channel));
        }
        _logger.info("send: " + counter.getAsDouble() + " m/s, received: "
                + getNumberMessagesReceivedPerSecond() + " m/s");

    } finally {
        closeQuietly(channels);
    }
}