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:io.indy.seni.util.ImageCache.java

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

    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        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).
        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) {

                // The removed entry is a standard BitmapDrawable

                // 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:eu.itesla_project.modules.RunSecurityAnalysisTool.java

@Override
public void run(CommandLine line) throws Exception {
    OfflineConfig config = OfflineConfig.load();
    String caseFormat = line.getOptionValue("case-format");
    Path caseDir = Paths.get(line.getOptionValue("case-dir"));
    String caseBaseName = line.getOptionValue("case-basename");
    Path outputCsvFile = Paths.get(line.getOptionValue("output-csv-file"));
    boolean detailed = line.hasOption("detailed");

    ContingenciesAndActionsDatabaseClient contingencyDb = config.getContingencyDbClientFactoryClass()
            .newInstance().create();/*from   w ww  . j a  v a 2 s.co m*/
    LoadFlowFactory loadFlowFactory = config.getLoadFlowFactoryClass().newInstance();

    try (ComputationManager computationManager = new LocalComputationManager()) {

        Importer importer = Importers.getImporter(caseFormat, computationManager);
        if (importer == null) {
            throw new RuntimeException("Format " + caseFormat + " not supported");
        }

        Map<String, Map<String, List<LimitViolation>>> statusPerContingencyPerCase = Collections
                .synchronizedMap(new TreeMap<>());

        Set<String> contingencyIds = Collections.synchronizedSet(new LinkedHashSet<>());

        if (caseBaseName != null) {
            System.out.println("loading case " + caseBaseName + " ...");

            // load the network
            Network network = importer.import_(new GenericReadOnlyDataSource(caseDir, caseBaseName),
                    new Properties());

            List<Contingency> contingencies = contingencyDb.getContingencies(network);
            contingencyIds.addAll(contingencies.stream().map(Contingency::getId).collect(Collectors.toList()));

            StaticSecurityAnalysis securityAnalysis = new StaticSecurityAnalysis(network, loadFlowFactory,
                    computationManager);

            statusPerContingencyPerCase.put(caseBaseName, securityAnalysis.run(contingencies));
        } else {
            Importers.importAll(caseDir, importer, true, network -> {
                try {
                    List<Contingency> contingencies = contingencyDb.getContingencies(network);
                    contingencyIds.addAll(
                            contingencies.stream().map(Contingency::getId).collect(Collectors.toList()));

                    StaticSecurityAnalysis securityAnalysis = new StaticSecurityAnalysis(network,
                            loadFlowFactory, computationManager);

                    statusPerContingencyPerCase.put(network.getId(), securityAnalysis.run(contingencies));
                } catch (Exception e) {
                    LOGGER.error(e.toString(), e);
                }
            }, dataSource -> System.out.println("loading case " + dataSource.getBaseName() + " ..."));
        }

        try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) {
            writer.write("base case");
            for (String contingencyId : contingencyIds) {
                writer.write(CSV_SEPARATOR);
                writer.write(contingencyId);
            }
            writer.newLine();

            for (Map.Entry<String, Map<String, List<LimitViolation>>> e : statusPerContingencyPerCase
                    .entrySet()) {
                String baseCaseName = e.getKey();
                Map<String, List<LimitViolation>> statusPerContingency = e.getValue();
                writer.write(baseCaseName);
                for (String contingencyId : contingencyIds) {
                    List<LimitViolation> violations = statusPerContingency.get(contingencyId);
                    writer.write(CSV_SEPARATOR);
                    writer.write(toString(violations, detailed));
                }
                writer.newLine();
            }
        }
    }
}

From source file:eu.itesla_project.security.RunSecurityAnalysisTool.java

@Override
public void run(CommandLine line) throws Exception {
    ComponentDefaultConfig config = new ComponentDefaultConfig();
    String caseFormat = line.getOptionValue("case-format");
    Path caseDir = Paths.get(line.getOptionValue("case-dir"));
    String caseBaseName = line.getOptionValue("case-basename");
    Path outputCsvFile = Paths.get(line.getOptionValue("output-csv-file"));
    boolean detailed = line.hasOption("detailed");

    ContingenciesProvider contingencyProvider = config.findFactoryImplClass(ContingenciesProviderFactory.class)
            .newInstance().create();//from www. jav  a  2 s  .co  m
    LoadFlowFactory loadFlowFactory = config.findFactoryImplClass(LoadFlowFactory.class).newInstance();

    try (ComputationManager computationManager = new LocalComputationManager()) {

        Importer importer = Importers.getImporter(caseFormat, computationManager);
        if (importer == null) {
            throw new RuntimeException("Format " + caseFormat + " not supported");
        }

        Map<String, Map<String, List<LimitViolation>>> statusPerContingencyPerCase = Collections
                .synchronizedMap(new TreeMap<>());

        Set<String> contingencyIds = Collections.synchronizedSet(new LinkedHashSet<>());

        if (caseBaseName != null) {
            System.out.println("loading case " + caseBaseName + " ...");

            // load the network
            Network network = importer.import_(new GenericReadOnlyDataSource(caseDir, caseBaseName),
                    new Properties());

            List<Contingency> contingencies = contingencyProvider.getContingencies(network);
            contingencyIds.addAll(contingencies.stream().map(Contingency::getId).collect(Collectors.toList()));

            StaticSecurityAnalysis securityAnalysis = new StaticSecurityAnalysis(network, loadFlowFactory,
                    computationManager);

            statusPerContingencyPerCase.put(caseBaseName, securityAnalysis.run(contingencies));
        } else {
            Importers.importAll(caseDir, importer, true, network -> {
                try {
                    List<Contingency> contingencies = contingencyProvider.getContingencies(network);
                    contingencyIds.addAll(
                            contingencies.stream().map(Contingency::getId).collect(Collectors.toList()));

                    StaticSecurityAnalysis securityAnalysis = new StaticSecurityAnalysis(network,
                            loadFlowFactory, computationManager);

                    statusPerContingencyPerCase.put(network.getId(), securityAnalysis.run(contingencies));
                } catch (Exception e) {
                    LOGGER.error(e.toString(), e);
                }
            }, dataSource -> System.out.println("loading case " + dataSource.getBaseName() + " ..."));
        }

        try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) {
            writer.write("base case");
            for (String contingencyId : contingencyIds) {
                writer.write(CSV_SEPARATOR);
                writer.write(contingencyId);
            }
            writer.newLine();

            for (Map.Entry<String, Map<String, List<LimitViolation>>> e : statusPerContingencyPerCase
                    .entrySet()) {
                String baseCaseName = e.getKey();
                Map<String, List<LimitViolation>> statusPerContingency = e.getValue();
                writer.write(baseCaseName);
                for (String contingencyId : contingencyIds) {
                    List<LimitViolation> violations = statusPerContingency.get(contingencyId);
                    writer.write(CSV_SEPARATOR);
                    writer.write(toString(violations, detailed));
                }
                writer.newLine();
            }
        }
    }
}

From source file:net.refractions.udig.catalog.internal.CatalogImpl.java

public CatalogImpl() {
    CatalogInfoImpl metadata = new CatalogInfoImpl();
    metadata.setTitle(Messages.CatalogImpl_localCatalog_title);
    try {//from w  ww. ja  v  a2  s . co  m
        metadata.setSource(new URL("http://localhost")); //$NON-NLS-1$
    } catch (MalformedURLException e) {
        // do nothing
    }

    this.metadata = metadata;
    catalogListeners = Collections.synchronizedSet(new WeakHashSet<IResolveChangeListener>());
}

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

@SetupRender
@Secured({ FactoryRoles.ROLE_ADMIN, FactoryRoles.ROLE_DLP_MANAGER, FactoryRoles.ROLE_QUARANTINE_MANAGER })
protected void setupRender() {
    if (selected == null) {
        selected = Collections.synchronizedSet(new HashSet<String>());
    } else {/*  w  ww.  j  a v  a 2s  .c om*/
        selected.clear();
    }

    if (filterBy == null) {
        filterBy = MailFilterBy.NO_FILTER;
    }
}

From source file:org.jboss.tools.openshift.internal.ui.models.ObservableResourceCache.java

private void cacheBuildConfigByOutput(IBuildConfig config) {
    String imageRef = imageRef(config);
    synchronized (imageRefToBuildConfigs) {
        if (!imageRefToBuildConfigs.containsKey(imageRef)) {
            imageRefToBuildConfigs.put(imageRef, Collections.synchronizedSet(new HashSet<>()));
        }//from   ww  w.  jav  a  2  s  .co  m
        imageRefToBuildConfigs.get(imageRef).add(config);
    }
}

From source file:org.apache.hadoop.mapred.buffer.net.BufferExchangeSink.java

public BufferExchangeSink(JobConf conf, InputCollector<K, V> collector, Task task) throws IOException {
    this.conf = conf;
    this.progress = new Progress();
    this.ownerid = task.getTaskID();
    this.collector = collector;
    this.maxConnections = conf.getInt("mapred.reduce.parallel.copies", 20);

    this.task = task;
    this.numInputs = task.getNumberOfInputs();
    this.inputProgress = new HashMap<TaskID, Float>();

    this.cursor = new HashMap<TaskID, Position>();
    this.syncMapPos = new HashMap<Long, Integer>();
    this.syncMaps = conf.getInt("mapred.iterative.partitions", 1);
    this.syncReducePos = new HashMap<Long, Integer>();
    this.syncReduces = conf.getInt("mapred.iterative.partitions", 1);

    this.executor = Executors.newFixedThreadPool(Math.min(maxConnections, Math.max(numInputs, 5)));
    this.handlers = Collections.synchronizedSet(new HashSet<Handler>());
    this.successful = Collections.synchronizedSet(new HashSet<TaskID>());

    /* The server socket and selector registration */
    this.server = ServerSocketChannel.open();
    this.server.configureBlocking(true);
    this.server.socket().bind(new InetSocketAddress(0));
}

From source file:com.hyphenate.easeui.utils.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *//*from ww  w. j av a  2 s  .co m*/
private void init(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 (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:com.example.nanchen.aiyaschoolpush.im.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 * /*from  w w w  . j  a v a 2  s.  c o  m*/
 * @param cacheParams
 *            The cache parameters to initialize the cache
 */
private void init(ImageCacheParams cacheParams) {
    ImageCacheParams 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).
        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.apache.bookkeeper.statelib.impl.kv.RocksdbKVStore.java

public RocksdbKVStore() {
    // initialize the iterators set
    this.kvIters = Collections.synchronizedSet(Sets.newHashSet());
}