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:com.github.programmerr47.vkgroups.imageloading.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *//*w w w .j a  v  a 2 s.  c  om*/
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

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

        // 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).
        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) {
                // 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<>(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;
            }
        };
    }
    //END_INCLUDE(init_memory_cache)

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}

From source file:com.test.displaybitmaps.imagemanager.ImageCache.java

/**
 * Set up the image-cache params, providing all parameters.
 * // w  ww .ja v a2  s .c  o m
 * @param cacheParams
 *            The cache parameters to initialize the cache
 */
public void setupImageCacheParams(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        Log.d(TAG, "Memory cache created (size = " + mCacheParams.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 (Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
            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 (Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
                        // 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;
            }
        };
    }
    // END_INCLUDE(init_memory_cache)

    // By default the disk cache is not initialized here as it should be
    // initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}

From source file:com.offbynull.portmapper.pcp.PcpDiscovery.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  a v  a 2 s . c  o 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) {
                foundGateways.add(sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(1100);
        MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"),
                0L);
        mpr.dump(outBuf, InetAddress.getByAddress(new byte[4])); // should get back an error for this, but this
                                                                 // should be fine because all we're looking for is a response, not
                                                                 // nessecarily a correct response -- self address being sent is
                                                                 // 0.0.0.0 (IPV4)
                                                                 //
                                                                 // also, we need to pass in MAP because Apple's garbage routers
                                                                 // give back NATPMP responses when you pass in ANNOUNCE

        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();
        }
    }

    foundGateways.retainAll(potentialGateways); // just incase we get back some unsolicited responses
    return new HashSet<>(foundGateways);
}

From source file:org.acegisecurity.concurrent.SessionRegistryImpl.java

public synchronized void registerNewSession(String sessionId, Object principal) {
    Assert.hasText(sessionId, "SessionId required as per interface contract");
    Assert.notNull(principal, "Principal required as per interface contract");

    if (logger.isDebugEnabled()) {
        logger.debug("Registering session " + sessionId + ", for principal " + principal);
    }/*from   w  w  w .j av a2s . c  o m*/

    if (getSessionInformation(sessionId) != null) {
        removeSessionInformation(sessionId);
    }

    sessionIds.put(sessionId, new SessionInformation(principal, sessionId, new Date()));

    Set sessionsUsedByPrincipal = (Set) principals.get(principal);

    if (sessionsUsedByPrincipal == null) {
        sessionsUsedByPrincipal = Collections.synchronizedSet(new HashSet());
    }

    sessionsUsedByPrincipal.add(sessionId);

    principals.put(principal, sessionsUsedByPrincipal);
}

From source file:com.android.simpleimageloader.image.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 * /*from  ww w.jav a  2  s  . c  o  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 (BuildConfig.DEBUG) {
        Log.d(TAG, "Memory cache created (size = " + mCacheParams.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>>());
    }

    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;
        }
    };
    // END_INCLUDE(init_memory_cache)
    initDiskCache();
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Set<UpnpIgdDevice> scanForDevices(InetSocketAddress multicastSocketAddress,
        Set<InetAddress> localAddresses, String searchQuery) throws IOException, InterruptedException {

    final Set<UpnpIgdDevice> ret = Collections.synchronizedSet(new HashSet<UpnpIgdDevice>());
    final Map<Channel, InetAddress> bindMap = Collections.synchronizedMap(new HashMap<Channel, InetAddress>());

    UdpCommunicatorListener listener = new UdpCommunicatorListener() {

        @Override//from   ww  w.j av a2  s  .c om
        public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                ByteBuffer packet) {
            byte[] inPacket = ByteBufferUtils.copyContentsToArray(packet);

            String inStr;
            try {
                inStr = new String(inPacket, 0, inPacket.length, "US-ASCII");
            } catch (UnsupportedEncodingException uee) {
                return;
            }

            Matcher matcher;

            URI url;
            if ((matcher = LOCATION_PATTERN.matcher(inStr)).find()) {
                String urlStr = matcher.group(1);
                try {
                    url = new URI(urlStr);
                } catch (URISyntaxException urise) {
                    return;
                }
            } else {
                return;
            }

            String name = null;
            if ((matcher = SERVER_PATTERN.matcher(inStr)).find()) {
                name = matcher.group(1);
            }

            InetAddress localAddress = bindMap.get(channel);

            UpnpIgdDevice device = new UpnpIgdDevice(localAddress, sourceAddress.getAddress(), name, url);
            ret.add(device);
        }
    };

    UdpCommunicator comm = null;
    try {
        List<DatagramChannel> channels = new ArrayList<>();

        for (InetAddress localAddr : localAddresses) {
            DatagramChannel channel = DatagramChannel.open();
            channel.configureBlocking(false);
            channel.bind(new InetSocketAddress(localAddr, 0));
            channels.add(channel);

            bindMap.put(channel, localAddr);
        }

        comm = new UdpCommunicator(channels);
        comm.startAsync().awaitRunning();
        comm.addListener(listener);

        ByteBuffer searchQueryBuffer = ByteBuffer.wrap(searchQuery.getBytes("US-ASCII")).asReadOnlyBuffer();
        for (int i = 0; i < 3; i++) {
            for (DatagramChannel channel : channels) {
                comm.send(channel, multicastSocketAddress, searchQueryBuffer.asReadOnlyBuffer());
            }

            Thread.sleep(TimeUnit.SECONDS.toMillis(MAX_WAIT + 1));
        }

        return new HashSet<>(ret);
    } finally {
        if (comm != null) {
            try {
                comm.stopAsync().awaitTerminated(); // this stop should handle closing all the datagram channels
            } catch (IllegalStateException ise) { // NOPMD
                // do nothing
            }
        }
    }
}

From source file:mitm.djigzo.web.components.DLPPatternGrid.java

@SetupRender
public void setupGrid() {
    if (selected == null) {
        selected = Collections.synchronizedSet(new HashSet<String>());
    } else {/*from   www.  j av a2s .  co m*/
        selected.clear();
    }
}

From source file:org.apache.camel.itest.http.HttpTestServer.java

/**
 * Creates a new test server.//from w  ww. j a  v a 2  s  . c  om
 *
 * @param proc      the HTTP processors to be used by the server, or
 *                  <code>null</code> to use a
 *                  {@link #newProcessor default} processor
 * @param reuseStrat the connection reuse strategy to be used by the
 *                  server, or <code>null</code> to use
 *                  {@link #newConnectionReuseStrategy() default}
 *                  strategy.
 * @param params    the parameters to be used by the server, or
 *                  <code>null</code> to use
 *                  {@link #newDefaultParams default} parameters
 * @param sslcontext optional SSL context if the server is to leverage
 *                   SSL/TLS transport security
 */
public HttpTestServer(final BasicHttpProcessor proc, final ConnectionReuseStrategy reuseStrat,
        final HttpResponseFactory responseFactory, final HttpExpectationVerifier expectationVerifier,
        final HttpParams params, final SSLContext sslcontext) {
    this.handlerRegistry = new HttpRequestHandlerRegistry();
    this.workers = Collections.synchronizedSet(new HashSet<Worker>());
    this.httpservice = new HttpService(proc != null ? proc : newProcessor(),
            reuseStrat != null ? reuseStrat : newConnectionReuseStrategy(),
            responseFactory != null ? responseFactory : newHttpResponseFactory(), handlerRegistry,
            expectationVerifier, params != null ? params : newDefaultParams());
    this.sslcontext = sslcontext;
}

From source file:com.intuit.qboecoui.feeds.util.ImageCache.java

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

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

        if (BuildConfig.DEBUG) {
            CustomLog.logDebug(TAG,
                    "[Feed] ImageCache:Memory cache created (size = " + mCacheParams.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>>());
        }

        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()) {
                        if (mEvictAndRecycle) {
                            //QBM Mobile:: Take more control of Bitmap memory management.
                            Bitmap recycleBitmap = oldValue.getBitmap();
                            if (recycleBitmap != null) {
                                recycleBitmap.recycle();
                                recycleBitmap = null;
                            }
                        } else {
                            // 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;
            }
        };
    }

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}

From source file:fr.mby.portal.coreimpl.configuration.PropertiesConfigurationManager.java

/**
 * Tag the configuration key./*from   ww  w.jav  a2s . c  o m*/
 * 
 * @param key
 * @param tag
 */
protected void tagConfigurationKey(final String key, final String tag) {
    Set<String> keys = this.keysByTag.get(tag);
    if (keys == null) {
        keys = new TreeSet<String>();
        keys = Collections.synchronizedSet(keys);
        this.keysByTag.put(key, keys);
    }
    keys.add(key);
}