Example usage for java.util Collections synchronizedMap

List of usage examples for java.util Collections synchronizedMap

Introduction

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

Prototype

public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m) 

Source Link

Document

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

Usage

From source file:org.kuali.coeus.sys.impl.validation.ErrorReporterImpl.java

private Map<String, Collection<SoftError>> initializeSoftErrorMap() {
    Map<String, Collection<SoftError>> softMessageMap = Collections
            .synchronizedMap(new HashMap<String, Collection<SoftError>>() {
                private static final long serialVersionUID = 709850431504932842L;

                @Override/*w  ww.ja v a  2s. c  om*/
                public Collection<SoftError> get(Object key) {
                    return super.remove(key);
                }

            });
    GlobalVariables.getUserSession().addObject(KeyConstants.SOFT_ERRORS_KEY, softMessageMap);
    return softMessageMap;
}

From source file:org.apache.torque.engine.database.model.Column.java

/**
 * Creates a new column and set the name
 *
 * @param name column name//w ww. j  av a 2s .c o m
 */
public Column(String name) {
    this.name = name;
    options = Collections.synchronizedMap(new ListOrderedMap());
}

From source file:de.escidoc.core.aa.business.cache.RequestAttributesCache.java

/**
 * Creates the internal map holding the system objects (attributes) that shall be cached for a request.<br/>
 *
 * @return Returns a synchronized LRU map. The map size is taken from the static field
 *         <code>internalCacheSize</code> that has to be initialized before calling this method (this is not
 *         checked).//www.  jav  a 2  s.co  m
 */
@SuppressWarnings("unchecked")
private static Map<Object, Object> createInternalMap() {

    return Collections.synchronizedMap(new LRUMap(internalCacheSize));
}

From source file:org.apache.hadoop.fs.HarFileSystem.java

private synchronized void initializeMetadataCache(Configuration conf) {
    if (harMetaCache == null) {
        int cacheSize = conf.getInt(METADATA_CACHE_ENTRIES_KEY, METADATA_CACHE_ENTRIES_DEFAULT);
        harMetaCache = Collections.synchronizedMap(new LruCache<URI, HarMetaData>(cacheSize));
    }/*from   w  w  w.ja v  a  2 s  . c  o  m*/
}

From source file:com.heliosdecompiler.helios.LoadedFile.java

public void reset() {
    readDataQuick();/*from w  w  w  .ja va 2  s.com*/
    if (files.size() > 0) {
        // Read all data of potential class files
        Helios.submitBackgroundTask(() -> {
            Map<String, ClassNode> emptyClasses = new HashMap<>();
            files.entrySet().stream().filter(ent -> ent.getKey().endsWith(".class")).forEach(ent -> {
                try {
                    ClassReader classReader = new ClassReader(new ByteArrayInputStream(ent.getValue()));
                    ClassNode classNode = new ClassNode();
                    classReader.accept(classNode,
                            ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);

                    // Store by ClassNode name
                    emptyClasses.put(classNode.name, classNode);
                    // Also store by path
                    emptyClasses.put(ent.getKey(), classNode);
                } catch (Exception ignored) { //Malformed class
                }
            });
            // Lock the map
            this.emptyClasses = Collections.unmodifiableMap(emptyClasses);
            if (!this.isPath) {
                // Read the code as well
                // fixme If path jars are guarenteed to not require code then maybe we can merge emptyClasses and classes
                // fixme this seems to hog cpu cycles or something
                Helios.submitBackgroundTask(() -> {
                    Map<String, ClassNode> classes = new HashMap<>();
                    files.entrySet().stream().filter(ent -> ent.getKey().endsWith(".class")).forEach(ent -> {
                        try {
                            ClassReader classReader = new ClassReader(new ByteArrayInputStream(ent.getValue()));
                            ClassNode classNode = new ClassNode();
                            classReader.accept(classNode, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);

                            // Store by ClassNode name
                            classes.put(classNode.name, classNode);
                            // Also store by path
                            classes.put(ent.getKey(), classNode);
                        } catch (Exception ignored) { //Malformed class
                        }
                    });
                    // Lock the map
                    this.classes = Collections.unmodifiableMap(classes);
                });
            } else {
                this.classes = Collections.synchronizedMap(new HashMap<>());
            }
        });
    }
}

From source file:org.exoplatform.services.jcr.impl.core.query.lucene.CachingIndexReader.java

/**
 * Creates a new <code>CachingIndexReader</code> based on
 * <code>delegatee</code>/*from  www  .  j  av a2 s  .co  m*/
 *
 * @param delegatee the base <code>IndexReader</code>.
 * @param cache     a document number cache, or <code>null</code> if not
 *                  available to this reader.
 * @param initCache if the {@link #parents} cache should be initialized
 *                  when this index reader is constructed.
 * @throws IOException if an error occurs while reading from the index.
 */
CachingIndexReader(IndexReader delegatee, DocNumberCache cache, boolean initCache) throws IOException {
    super(delegatee);
    this.cache = cache;
    this.parents = new DocId[delegatee.maxDoc()];
    this.shareableNodes = new BitSet();
    TermDocs tDocs = delegatee.termDocs(new Term(FieldNames.SHAREABLE_NODE, ""));
    try {
        while (tDocs.next()) {
            shareableNodes.set(tDocs.doc());
        }
    } finally {
        tDocs.close();
    }
    this.cacheInitializer = new CacheInitializer(delegatee);
    if (initCache) {
        cacheInitializer.run();
    }
    // limit cache to 1% of maxDoc(), but at least 10.
    this.docNumber2uuid = Collections.synchronizedMap(new LRUMap(Math.max(10, delegatee.maxDoc() / 100)));
    this.termDocsCache = new TermDocsCache(delegatee, FieldNames.PROPERTIES);
}

From source file:com.hurence.logisland.connect.opc.CommonOpcSourceTask.java

@Override
public void start(Map<String, String> props) {
    setConfigurationProperties(props);/*from  w w w  .j  a va 2s.c  o m*/

    transferQueue = new LinkedTransferQueue<>();
    opcOperations = new SmartOpcOperations<>(createOpcOperations());
    ConnectionProfile connectionProfile = createConnectionProfile();
    host = connectionProfile.getConnectionUri().getHost();
    tagInfoMap = CommonUtils.parseTagsFromProperties(props).stream()
            .collect(Collectors.toMap(TagInfo::getTagId, Function.identity()));
    minWaitTime = Math.min(10, tagInfoMap.values().stream().map(TagInfo::getSamplingInterval)
            .mapToLong(Duration::toMillis).min().getAsLong());
    opcOperations.connect(connectionProfile);
    if (!opcOperations.awaitConnected()) {
        throw new ConnectException("Unable to connect");
    }

    //set up polling source emission
    pollingScheduler = Executors.newSingleThreadScheduledExecutor();
    streamingThread = Executors.newSingleThreadExecutor();
    Map<Duration, List<TagInfo>> pollingMap = tagInfoMap.values().stream()
            .filter(tagInfo -> StreamingMode.POLL.equals(tagInfo.getStreamingMode()))
            .collect(Collectors.groupingBy(TagInfo::getSamplingInterval));
    final Map<String, OpcData> lastValues = Collections.synchronizedMap(new HashMap<>());
    pollingMap.forEach((k, v) -> pollingScheduler.scheduleAtFixedRate(() -> {
        final Instant now = Instant.now();
        v.stream().map(TagInfo::getTagId).map(lastValues::get).filter(Functions.not(Objects::isNull))
                .map(data -> Pair.of(now, data)).forEach(transferQueue::add);

    }, 0, k.toNanos(), TimeUnit.NANOSECONDS));
    //then subscribe for all
    final SubscriptionConfiguration subscriptionConfiguration = new SubscriptionConfiguration()
            .withDefaultSamplingInterval(Duration.ofMillis(10_000));
    tagInfoMap.values().forEach(tagInfo -> subscriptionConfiguration
            .withTagSamplingIntervalForTag(tagInfo.getTagId(), tagInfo.getSamplingInterval()));
    running.set(true);
    streamingThread.submit(() -> {
        while (running.get()) {
            try {
                createSessionIfNeeded();
                if (session == null) {
                    return;
                }

                session.stream(subscriptionConfiguration,
                        tagInfoMap.keySet().toArray(new String[tagInfoMap.size()])).forEach(opcData -> {
                            if (tagInfoMap.get(opcData.getTag()).getStreamingMode()
                                    .equals(StreamingMode.SUBSCRIBE)) {
                                transferQueue.add(Pair.of(
                                        hasServerSideSampling() ? opcData.getTimestamp() : Instant.now(),
                                        opcData));
                            } else {
                                lastValues.put(opcData.getTag(), opcData);
                            }
                        });
            } catch (Exception e) {
                if (running.get()) {
                    logger.warn("Stream interrupted while reading from " + host, e);
                    safeCloseSession();
                    lastValues.clear();

                }
            }
        }
    });

}

From source file:com.frameworkset.platform.cms.driver.i18n.CmsLocaleManager.java

/**
 * Initializes a new CmsLocaleManager, called from the configuration.<p>
 *///from  w  w  w  .  jav  a 2  s  . co m
public CmsLocaleManager() {

    setDefaultLocale();
    m_availableLocales = new ArrayList();
    m_defaultLocales = new ArrayList();
    m_localeHandler = new CmsDefaultLocaleHandler();
    //        if (CmsLog.INIT.isInfoEnabled()) {
    //            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_I18N_CONFIG_START_0));
    //        }

    LRUMap lruMap = new LRUMap(256);
    m_localeCache = Collections.synchronizedMap(lruMap);
    //        CmsMemoryMonitor monitor = OpenCms.getMemoryMonitor();
    //        if ((monitor != null) && monitor.enabled()) {
    //            // map must be of type "LRUMap" so that memory monitor can acecss all information
    //            monitor.register(this.getClass().getName() + ".m_localeCache", lruMap);
    //        }

    // register this object as event listener
    //        OpenCms.addCmsEventListener(this, new int[] {I_CmsEventListener.EVENT_CLEAR_CACHES});
}

From source file:org.romaframework.aspect.view.ViewAspectAbstract.java

public ViewAspectAbstract() {
    Controller.getInstance().registerListener(SessionListener.class, this);
    Controller.getInstance().registerListener(SchemaReloadListener.class, this);

    objectsForms = Collections.synchronizedMap(new HashMap<SessionInfo, Map<Object, ViewComponent>>());
}

From source file:org.jboss.dashboard.profiler.ThreadProfile.java

public ThreadProfile() {
    this.stackTraces = new ArrayList<StackTrace>();
    this.maxThreadDurationInMillis = 120000;
    this.maxStackTraceLength = 500;
    this.contextProperties = Collections.synchronizedMap(new LinkedHashMap<String, Object>());
    this.logEvents = null;
    this.maxLogEvents = 10000;
    this.logOverflow = false;
    this.errorReport = null;
    this.targetThread = false;
    clearStackTraces();//from   w  w w . ja va2s .c om
}