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:ch.chrigu.datastructures.demo.instances.CollectionInstance.java

/**
 * The best matching {@link Collections}'s synchronized... function is applied.
 *///from   www .j ava2s . c  o  m
private Collection<T> synchronizedCollection(Collection<T> instance) {
    if (instance instanceof List) {
        return Collections.synchronizedList((List<T>) instance);
    }
    if (instance instanceof Set) {
        if (instance instanceof NavigableSet) {
            return Collections.synchronizedNavigableSet((NavigableSet<T>) instance);
        }
        return Collections.synchronizedSet((Set<T>) instance);
    }
    return Collections.synchronizedCollection(instance);
}

From source file:org.zaproxy.zap.extension.spider.SpiderScan.java

public SpiderScan(ExtensionSpider extension, SpiderParam spiderParams, Target target, URI spiderURI,
        User scanUser, int scanId) {
    lock = new ReentrantLock();
    this.scanId = scanId;

    numberOfURIsFound = new AtomicInteger();
    foundURIs = Collections.synchronizedSet(new HashSet<String>());
    resourcesFound = Collections.synchronizedList(new ArrayList<SpiderResource>());
    foundURIsOutOfScope = Collections.synchronizedSet(new HashSet<String>());

    state = State.NOT_STARTED;/*w  w w  .j  av a  2s . co m*/

    spiderThread = new SpiderThread(extension, spiderParams, "SpiderApi-" + scanId, this);

    spiderThread.setStartURI(spiderURI);
    spiderThread.setStartNode(target.getStartNode());
    spiderThread.setScanContext(target.getContext());
    spiderThread.setScanAsUser(scanUser);
    spiderThread.setJustScanInScope(target.isInScopeOnly());
    spiderThread.setScanChildren(target.isRecurse());
}

From source file:com.seun.gallery.util.ImageCache.java

/**
 * Initialize the cache/*  w w  w.j  a v a 2 s .c  o m*/
 */
private void init(int memoryCacheSize) {
    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (DEBUG) {
        Log.d(TAG, "Memory cache created (size = " + memoryCacheSize + ")");
    }

    // 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 >= Build.VERSION_CODES.HONEYCOMB) {
        mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
    }

    mMemoryCache = new LruCache<String, BitmapDrawable>(memoryCacheSize) {

        /**
         * 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 >= Build.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)
}

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

@Test
public void test1InstanceConcurrent() throws Exception {
    final MulticastClusterChannel channel = channel(U1);
    try {/* w  w w  . j  a va 2s.  c o m*/
        final int numberOfWorkers = 4;
        final int numberOfMessages = 1000;
        final Set<String> messagesSend = Collections.synchronizedSet(new HashSet<String>());
        final List<Worker> workers = createWorkersFor(numberOfWorkers, numberOfMessages, messagesSend, channel,
                null);
        final StopWatch stopWatch = new StopWatch();
        run(workers);
        assertThat(stopWatch.getCurrentDuration(),
                isLessThan(new Duration("7ms").multiplyBy(numberOfMessages)));
        assertThat(messagesSend, hasSize(numberOfWorkers * numberOfMessages));
    } finally {
        closeQuietly(channel);
    }
}

From source file:org.apache.taverna.activities.interaction.InteractionRecorder.java

private Set<String> getResourceSet(final String runId, final String interactionId) {
    final Map<String, Set<String>> interactionMap = getInteractionMap(runId);
    Set<String> resourceSet = interactionMap.get(interactionId);
    if (resourceSet == null) {
        resourceSet = Collections.synchronizedSet(new HashSet<String>());
        interactionMap.put(interactionId, resourceSet);
    }//from   w  w  w .  j  a v  a  2  s . c  o m
    return resourceSet;
}

From source file:org.apache.hadoop.mapreduce.v2.app.rm.preemption.CheckpointAMPreemptionPolicy.java

public CheckpointAMPreemptionPolicy() {
    this(Collections.synchronizedSet(new HashSet<TaskAttemptId>()),
            Collections.synchronizedSet(new HashSet<TaskAttemptId>()),
            Collections.synchronizedMap(new HashMap<TaskId, TaskCheckpointID>()),
            Collections.synchronizedMap(new HashMap<TaskAttemptId, Resource>()));
}

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

@Test
public void test1InstanceConcurrent() throws Exception {
    final TcpClusterChannel channel = channel(U1);
    channel.init();//from  w  ww .  j  ava 2s  . co  m
    try {
        final int numberOfWorkers = 5;
        final int numberOfMessages = 1000;
        final Set<String> messagesSend = Collections.synchronizedSet(new HashSet<String>());
        final List<Worker> workers = createWorkersFor(numberOfWorkers, numberOfMessages, messagesSend, channel,
                null);
        final StopWatch stopWatch = new StopWatch();
        run(workers);
        assertThat(stopWatch.getCurrentDuration(),
                isLessThan(new Duration("7ms").multiplyBy(numberOfMessages)));
        assertThat(messagesSend, hasSize(numberOfWorkers * numberOfMessages));

        _logger.info("Nodes status of (" + channel + "):\n" + formatNodesStatusOf(channel));
    } finally {
        closeQuietly(channel);
    }
}

From source file:org.nuxeo.runtime.model.impl.ComponentPersistence.java

public ComponentPersistence(OSGiRuntimeService runtime) {
    this.runtime = runtime;
    root = new File(Environment.getDefault().getData(), "components");
    fileLock = new ReentrantReadWriteLock();
    sysrc = runtime.getContext();//from w ww  . j  a  v  a2  s  .c  om
    persistedComponents = Collections.synchronizedSet(new HashSet<>());
}

From source file:org.beangle.security.core.session.impl.MemSessionRegistry.java

public void register(Authentication auth, String sessionid) throws SessionException {
    Sessioninfo existed = getSessioninfo(sessionid);
    String principal = auth.getName();
    // ???/*w ww.  java 2s .  co m*/
    if (null != existed && ObjectUtils.equals(existed.getUsername(), principal))
        return;
    // ????
    boolean success = controller.onRegister(auth, sessionid, this);
    if (!success)
        throw new SessionException("security.OvermaxSession");
    // ??
    if (null != existed) {
        existed.addRemark(" expired with replacement.");
        remove(sessionid);
    }
    // 
    sessionids.put(sessionid, sessioninfoBuilder.build(auth, controller.getServerName(), sessionid));
    Set<String> sessionsUsedByPrincipal = principals.get(principal);
    if (sessionsUsedByPrincipal == null) {
        sessionsUsedByPrincipal = Collections.synchronizedSet(new HashSet<String>(4));
        principals.put(principal, sessionsUsedByPrincipal);
    }
    sessionsUsedByPrincipal.add(sessionid);
}

From source file:org.amplafi.hivemind.factory.mock.MockBuilderFactoryImpl.java

public MockBuilderFactoryImpl(boolean shareMocksAcrossThreads) {
    this.shareMocksAcrossThreads = shareMocksAcrossThreads;

    mockOverride = new SwitchableThreadLocal<Set<Class<?>>>(this.shareMocksAcrossThreads) {
        @Override/*  ww  w . java 2 s.  c  o  m*/
        protected Set<Class<?>> initialValue() {
            return Collections.synchronizedSet(new HashSet<Class<?>>());
        }
    };

    dontMockOverride = new SwitchableThreadLocal<Set<Class<?>>>(this.shareMocksAcrossThreads) {
        @Override
        protected Set<Class<?>> initialValue() {
            return Collections.synchronizedSet(new HashSet<Class<?>>());
        }
    };

    mockObjectsMap = new SwitchableThreadLocal<Map<Class<?>, Object>>(this.shareMocksAcrossThreads) {
        @Override
        protected Map<Class<?>, Object> initialValue() {
            return new ConcurrentHashMap<Class<?>, Object>();
        }
    };
    mockObjectsByNameMap = new SwitchableThreadLocal<Map<String, Object>>(this.shareMocksAcrossThreads) {
        @Override
        protected Map<String, Object> initialValue() {
            return new ConcurrentHashMap<String, Object>();
        }
    };
}