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.LexGrid.LexBIG.Impl.Extensions.GenericExtensions.LexBIGServiceConvenienceMethodsImpl.java

/**
 * Return the map used to cache hierarchy root code information, which maps
 * from key (derived from request parameters) to an array of root codes
 * (String[])./*from  ww w.j  a v a 2  s.  com*/
 * <p>
 * Note: Methods requiring the cache should invoke this method rather than
 * directly referencing the class variable in order to allow lazy
 * initialization.
 */
@LgClientSideSafe
protected Map getCache_HRootCodes() {
    if (cache_hRootCodes_ == null)
        cache_hRootCodes_ = Collections.synchronizedMap(new LRUMap(128));
    return cache_hRootCodes_;
}

From source file:org.LexGrid.LexBIG.Impl.Extensions.GenericExtensions.LexBIGServiceConvenienceMethodsImpl.java

/**
 * Return the map used to cache hierarchy root existence, which maps from
 * key (derived from request parameters) to a Boolean value.
 * <p>//ww  w. j  a  v  a 2  s . c  o m
 * Note: Methods requiring the cache should invoke this method rather than
 * directly referencing the class variable in order to allow lazy
 * initialization.
 */
@LgClientSideSafe
protected Map getCache_HPathToRootExists() {
    if (cache_hPathToRootExists_ == null)
        cache_hPathToRootExists_ = Collections.synchronizedMap(new LRUMap(2048));
    return cache_hPathToRootExists_;
}

From source file:com.topsec.tsm.sim.report.model.ReportModel.java

/**
 *  1.mail 2.??/*from w w w .  ja  v  a2 s .co  m*/
 * 
 * @param RptMasterTbService
 *            rptMasterTbImp DAO
 * @param ExpStruct
 *            exp 
 * @param HttpServletRequest
 *            request HttpServletRequest
 * @return LinkedHashMap<String, List> exp?
 * @throws Exception
 *             2.
 */
public static LinkedHashMap<String, List> expMstReport(RptMasterTbService rptMasterTbImp, ExpStruct exp,
        HttpServletRequest request) throws Exception {
    String mstRptId = exp.getMstrptid();// ID
    Integer mstRptIdInt = 0;
    if (!GlobalUtil.isNullOrEmpty(mstRptId)) {
        mstRptIdInt = Integer.valueOf(mstRptId);
    }
    String mstSql = ReportUiConfig.MstSubSql;
    Object[] subParam = { mstRptIdInt };
    //      List<Map<String,Object>> subResult = rptMasterTbImp.queryTmpList(mstSql, subParam);

    List<Map<String, Object>> subResult = new ArrayList<Map<String, Object>>();
    Map<Integer, Integer> rowColumns = new HashMap<Integer, Integer>();

    List<Map<String, Object>> subResultTemp = rptMasterTbImp.queryTmpList(mstSql, subParam);
    if (subResultTemp.size() > 0) {
        Map subMap = subResultTemp.get(0);
        String viewItem = StringUtil.toString(subMap.get("viewItem"), "");
        if (viewItem.indexOf("2") < 0) {
            exp.setRptType(ReportUiConfig.rptDirection);
            String[] time = ReportUiUtil.getExpTime("month");
            exp.setRptTimeS(time[0]);
            exp.setRptTimeE(time[1]);
        }
    }
    int evtRptsize = subResultTemp.size();
    if (!GlobalUtil.isNullOrEmpty(subResultTemp)) {
        subResult.addAll(subResultTemp);
    }
    ReportBean bean = new ReportBean();
    if (!GlobalUtil.isNullOrEmpty(request)) {
        bean = ReportUiUtil.tidyFormBean(bean, request);
    }
    String nodeType = bean.getNodeType();
    String dvcaddress = bean.getDvcaddress();
    DataSourceService dataSourceService = (DataSourceService) SpringContextServlet.springCtx
            .getBean("dataSourceService");
    if (!GlobalUtil.isNullOrEmpty(bean.getDvctype()) && bean.getDvctype().startsWith("Profession/Group")
            && !GlobalUtil.isNullOrEmpty(nodeType) && !GlobalUtil.isNullOrEmpty(dvcaddress)) {
        Map map = TopoUtil.getAssetEvtMstMap();
        String mstIds = null;
        List<SimDatasource> simDatasources = dataSourceService.getByIp(dvcaddress);
        if (!GlobalUtil.isNullOrEmpty(simDatasources)) {
            mstIds = "";
            for (SimDatasource simDatasource : simDatasources) {
                if (map.containsKey(simDatasource.getSecurityObjectType())) {
                    mstIds += map.get(simDatasource.getSecurityObjectType()).toString() + ":::";
                } else {
                    String keyString = getStartStringKey(map, simDatasource.getSecurityObjectType());
                    if (!GlobalUtil.isNullOrEmpty(keyString)) {
                        mstIds += map.get(keyString).toString() + ":::";
                    }
                }
            }
            if (mstIds.length() > 3) {
                mstIds = mstIds.substring(0, mstIds.length() - 3);
            }
        } else {
            if (map.containsKey(nodeType)) {
                mstIds = map.get(nodeType).toString();
            } else {
                String keyString = getStartStringKey(map, nodeType);
                if (!GlobalUtil.isNullOrEmpty(keyString)) {
                    mstIds = map.get(keyString).toString();
                }
            }
        }
        if (!GlobalUtil.isNullOrEmpty(mstIds)) {
            String[] mstIdArr = mstIds.split(":::");
            for (String string : mstIdArr) {
                List<Map<String, Object>> subTemp = rptMasterTbImp.queryTmpList(mstSql,
                        new Object[] { StringUtil.toInt(string, 5) });
                if (!GlobalUtil.isNullOrEmpty(subTemp)) {
                    int maxCol = 0;
                    if (!GlobalUtil.isNullOrEmpty(rowColumns)) {
                        maxCol = getMaxOrMinKey(rowColumns, 1);
                    }
                    for (Map map2 : subTemp) {
                        Integer row = (Integer) map2.get("subRow") + maxCol;
                        map2.put("subRow", row);
                    }
                    subResult.addAll(subTemp);
                }
            }
        }
    }

    if (!GlobalUtil.isNullOrEmpty(bean.getDvctype()) && bean.getDvctype().startsWith("Comprehensive")) {
        List<String> dvcTypes = dvcTypes = new ArrayList<String>();
        dvcTypes.add(bean.getDvctype().replace("Comprehensive", ""));

        List<String> mstrptidAndNodeTypeList = new ArrayList<String>();
        setMstIdAndScanNodeType(dvcTypes, mstrptidAndNodeTypeList);
        subResultTemp = null;
        if (!GlobalUtil.isNullOrEmpty(mstrptidAndNodeTypeList)) {
            subResultTemp = rptMasterTbImp.queryTmpList(ReportUiConfig.MstSubSql,
                    new Object[] { StringUtil.toInt((mstrptidAndNodeTypeList.get(0).split("IDandNODEtype"))[0],
                            StringUtil.toInt(bean.getTalTop(), 5)) });
            Map<Integer, Integer> rowColumnsTeMap = ReportModel.getRowColumns(subResultTemp);
            evtRptsize = subResultTemp.size();
            if (!GlobalUtil.isNullOrEmpty(subResultTemp)) {
                for (Map map2 : subResultTemp) {
                    map2.put("subject", (mstrptidAndNodeTypeList.get(0).split("IDandNODEtype"))[1]);
                }
                subResult.addAll(subResultTemp);
                rowColumns.putAll(rowColumnsTeMap);
            }

            int len = mstrptidAndNodeTypeList.size();
            for (int i = 1; i < len; i++) {
                String mstrptidAndNodeType = mstrptidAndNodeTypeList.get(i);
                String string = mstrptidAndNodeType.split("IDandNODEtype")[0];
                List<Map<String, Object>> subTemp = rptMasterTbImp.queryTmpList(ReportUiConfig.MstSubSql,
                        new Object[] { StringUtil.toInt(string, StringUtil.toInt(bean.getTalTop(), 5)) });
                if (!GlobalUtil.isNullOrEmpty(subTemp)) {
                    int maxCol = 0;
                    if (!GlobalUtil.isNullOrEmpty(rowColumns)) {
                        maxCol = getMaxOrMinKey(rowColumns, 1);
                    }
                    for (Map map2 : subTemp) {
                        Integer row = (Integer) map2.get("subRow") + maxCol;
                        map2.put("subRow", row);
                        map2.put("subject", mstrptidAndNodeType.split("IDandNODEtype")[1]);
                    }
                    subResult.addAll(subTemp);
                    Map<Integer, Integer> rowColTemp = ReportModel.getRowColumns(subTemp);
                    rowColumns.putAll(rowColTemp);
                }
            }
        }
    }

    List<ExpDateStruct> expList = new ArrayList<ExpDateStruct>(); // ?
    Map<ReportExecutor.SubjectKey, Map<Integer, ExpDateStruct>> exportMap = Collections
            .synchronizedMap(new LinkedHashMap());
    ExecutorService threadPool = Executors.newFixedThreadPool(subResult.size(),
            new TsmThreadFactory("ReportSubjectExport"));
    LinkedHashMap<String, List> expMap = null;
    try {
        List<ReportExecutor> tasks = new ArrayList<ReportExecutor>(subResult.size());
        int order = 0;
        for (Map sub : subResult) {
            order += 100;
            tasks.add(new ReportExecutor(order, rptMasterTbImp, exp, exportMap, expList, sub, request,
                    SID.currentUser()));
        }
        threadPool.invokeAll(tasks);
        expMap = new LinkedHashMap<String, List>(exportMap.size());
        for (Map.Entry<ReportExecutor.SubjectKey, Map<Integer, ExpDateStruct>> entry : exportMap.entrySet()) {
            expMap.put(entry.getKey().subject, new ArrayList(entry.getValue().values()));
        }
    } finally {
        threadPool.shutdownNow();
    }
    return expMap;
}

From source file:lucee.runtime.config.ConfigImpl.java

public void putCachedPageSource(String pathWithCFC, PageSource ps) {
    if (componentPathCache == null)
        componentPathCache = Collections.synchronizedMap(new HashMap<String, PageSource>());//MUSTMUST new ReferenceMap(ReferenceMap.SOFT,ReferenceMap.SOFT); 
    componentPathCache.put(pathWithCFC.toLowerCase(), ps);
}

From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java

/**
 * Reflectively set all the attributes in {@code original} to the values given
 * by {@code updated}. This has the effect of making {@code original} the
 * same as {@code updated} but without requiring the client code to change the
 * object reference to {@code original}, which may be referenced in many places.
 *
 * <p>//from w w w. j  a va2s. com
 * Where a field is a Collection, the existing collection is emptied and all the
 * objects from that field in {@code updated} are added in the same order to the
 * collection in {@code original}. Whether this order is maintained depends on
 * the type of collection in {@code original} (a list will maintain order, a set
 * typically won't).
 * </p>
 *
 * <p>
 * Fields that are static, transient or final are ignored, as are any fields annotated
 * with the {@code @XmlTransient} annotation.
 * </p>
 *
 * <p>
 * Note that fields within the original object that are objects themselves (as opposed to
 * primitives) are replaced with the new versions. References to sub objects are therefore
 * no longer valid.
 * </p>
 *
 * @param original The original object that was provided in the call and needs updating.
 * @param updated The version of the object returned from the LIMS with the current state.
 *
 * @throws IllegalArgumentException if either {@code original} or {@code updated}
 * are null, or are of different classes.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void reflectiveUpdate(Object original, Object updated) {
    if (original == null) {
        throw new IllegalArgumentException("original cannot be null");
    }
    if (updated == null) {
        throw new IllegalArgumentException("updated cannot be null");
    }

    if (!original.getClass().equals(updated.getClass())) {
        throw new IllegalArgumentException("original and updated are of different classes");
    }

    Class<?> clazz = original.getClass();

    do {
        Map<String, java.lang.reflect.Field> fieldMap = updaterFields.get(clazz);
        if (fieldMap == null) {
            fieldMap = Collections.synchronizedMap(new HashMap<String, java.lang.reflect.Field>());
            updaterFields.put(clazz, fieldMap);

            Class<?> currentClass = clazz;
            while (!Object.class.equals(currentClass)) {
                for (java.lang.reflect.Field field : currentClass.getDeclaredFields()) {
                    // Skip transient and XmlTransient fields.
                    if ((field.getModifiers() & REFLECTIVE_UPDATE_MODIFIER_MASK) == 0
                            && field.getAnnotation(XmlTransient.class) == null) {
                        field.setAccessible(true);
                        java.lang.reflect.Field clash = fieldMap.put(field.getName(), field);
                        if (clash != null) {
                            throw new AssertionError("There is more than one field with the name '"
                                    + field.getName() + " in the class hierarchy of " + clazz.getName() + " ("
                                    + getShortClassName(field.getDeclaringClass()) + " and "
                                    + getShortClassName(clash.getDeclaringClass()) + ")");
                        }
                    }
                }
                currentClass = currentClass.getSuperclass();
            }
        }

        for (java.lang.reflect.Field field : fieldMap.values()) {
            try {
                Object originalValue = field.get(original);
                Object updatedValue = field.get(updated);

                if (Collection.class.isAssignableFrom(field.getDeclaringClass())) {
                    Collection originalCollection = (Collection) originalValue;
                    Collection updatedCollection = (Collection) updatedValue;

                    if (originalCollection != null) {
                        originalCollection.clear();
                        if (updatedCollection != null) {
                            originalCollection.addAll(updatedCollection);
                        }
                    } else {
                        if (updatedCollection != null) {
                            // Getting as a property should create the collection object.
                            originalCollection = (Collection) PropertyUtils.getProperty(original,
                                    field.getName());
                            originalCollection.addAll(updatedCollection);
                        }
                    }
                } else if (Map.class.isAssignableFrom(field.getDeclaringClass())) {
                    throw new AssertionError("I didn't think we'd be dealing with maps: field "
                            + field.getName() + " on class " + field.getDeclaringClass().getName());
                } else {
                    field.set(original, updatedValue);
                }
            } catch (IllegalAccessException e) {
                logger.error("Cannot access the property {} on the class {}", field.getName(),
                        field.getDeclaringClass().getName());
                fieldMap.remove(field.getName());
            } catch (NoSuchMethodException e) {
                logger.error("There is no getter method for the property {} on the class {}", field.getName(),
                        field.getDeclaringClass().getName());
                fieldMap.remove(field.getName());
            } catch (InvocationTargetException e) {
                logger.error("Error while getting collection property {}", field.getName(),
                        e.getTargetException());
            } catch (ClassCastException e) {
                logger.error("Cannot cast a {} to a Collection.", e.getMessage());
            }
        }

        clazz = clazz.getSuperclass();
    } while (!Object.class.equals(clazz));
}

From source file:org.dihedron.strutlets.ActionContext.java

/**
 * Sets interceptor-specific data into the action context; this information 
 * is available through different calls and can be used to keep track of 
 * system status, such as number of calls for target, or number of accesses
 * by the same user etc. This method should only be used by interceptors, 
 * and the associated data should not be tampered with, to avoid unpredictable 
 * behaviour./*from w  w  w  .  ja  v  a  2  s. c o  m*/
 * 
 * @param interceptorId
 *   the namepaced id of the interceptor this data belongs to (see 
 *   {@link Interceptor#getId()} for details).
 * @param data
 *   the data object.
 */
public static void setInterceptorData(String interceptorId, Object data) {
    @SuppressWarnings("unchecked")
    Map<String, Object> map = (Map<String, Object>) getPortletAttribute(INTERCEPTOR_DATA_KEY);
    if (map == null) {
        map = Collections.synchronizedMap(new HashMap<String, Object>());
        setPortletAttribute(INTERCEPTOR_DATA_KEY, map);
    }
    map.put(interceptorId, data);
}

From source file:lucee.runtime.config.ConfigImpl.java

public void putCTInitFile(String key, InitFile initFile) {
    if (ctPatchCache == null)
        ctPatchCache = Collections.synchronizedMap(new HashMap<String, InitFile>());//MUSTMUST new ReferenceMap(ReferenceMap.SOFT,ReferenceMap.SOFT); 
    ctPatchCache.put(key.toLowerCase(), initFile);
}

From source file:org.sakaiproject.content.tool.ResourcesAction.java

/**
* Navigate in the resource hireachy/*from w w  w . java  2s.  c  o m*/
*/
public void doNavigate(RunData data) {
    logger.debug(this + ".doNavigate()");

    if (!"POST".equals(data.getRequest().getMethod())) {
        return;
    }

    SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

    if (state.getAttribute(STATE_SELECT_ALL_FLAG) != null
            && state.getAttribute(STATE_SELECT_ALL_FLAG).equals(Boolean.TRUE.toString())) {
        state.setAttribute(STATE_SELECT_ALL_FLAG, Boolean.FALSE.toString());
    }

    if (state.getAttribute(STATE_EXPAND_ALL_FLAG) != null
            && state.getAttribute(STATE_EXPAND_ALL_FLAG).equals(Boolean.TRUE.toString())) {
        state.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.FALSE.toString());
    }

    // save the current selections
    Set selectedSet = new TreeSet();
    String[] selectedItems = data.getParameters().getStrings("selectedMembers");
    if (selectedItems != null) {
        selectedSet.addAll(Arrays.asList(selectedItems));
    }
    state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);

    String collectionId = data.getParameters().getString("collectionId");
    String navRoot = data.getParameters().getString("navRoot");
    state.setAttribute(STATE_NAVIGATION_ROOT, navRoot);

    // the exception message

    try {
        ContentHostingService.checkCollection(collectionId);
    } catch (PermissionException e) {
        addAlert(state, rb.getString("notpermis3"));
    } catch (IdUnusedException e) {
        addAlert(state, rb.getString("notexist2"));
    } catch (TypeException e) {
        addAlert(state, rb.getString("notexist2"));
    }

    if (state.getAttribute(STATE_MESSAGE) == null) {
        String oldCollectionId = (String) state.getAttribute(STATE_COLLECTION_ID);
        // update this folder id in the set to be event-observed
        removeObservingPattern(oldCollectionId, state);
        addObservingPattern(collectionId, state);

        state.setAttribute(STATE_COLLECTION_ID, collectionId);

        Set<String> expandedCollections = getExpandedCollections(state);

        Map sortMap = Collections.synchronizedMap(setStateAttributeExpandedFolderSortMap(state));

        // sync over sortMap removal
        Iterator it = expandedCollections.iterator();
        synchronized (sortMap) {
            while (it.hasNext()) {
                String id = (String) it.next();
                if (id.startsWith(collectionId)) {
                    sortMap.remove(id);
                    removeObservingPattern(id, state);
                }
            }
        }

        SortedSet newExpandedCollections = new TreeSet<String>();
        for (String id : expandedCollections) {
            if (!id.startsWith(collectionId)) {
                newExpandedCollections.add(id);
            }
        }
        newExpandedCollections.add(collectionId);

        expandedCollections.clear();
        expandedCollections.addAll(newExpandedCollections);
    }

}

From source file:gov.noaa.pfel.coastwatch.Projects.java

/** Test various hashmap implementations. */
public static void testHashMaps() {
    String2.log("test regular HashMap");
    long time = System.currentTimeMillis();
    HashMap hashmap = new HashMap();
    for (int i = 0; i < 1000; i++) {
        String s = "" + i;
        hashmap.put(s, s);/*from   ww w.ja  v  a2 s .com*/
    }
    String max = "";
    for (int i = 0; i < 1000; i++) {
        for (int j = 0; j < 1000; j++) {
            String s = (String) hashmap.get("" + j);
            max = s.length() > max.length() ? s : max;
        }
    }
    String2.log("test regular hashMap finished longest=" + max + " time=" + (System.currentTimeMillis() - time)
            + "ms"); //282     

    //***
    String2.log("test synchronized HashMap");
    time = System.currentTimeMillis();
    Map smap = Collections.synchronizedMap(new HashMap());
    for (int i = 0; i < 1000; i++) {
        String s = "" + i;
        smap.put(s, s);
    }
    max = "";
    for (int i = 0; i < 1000; i++) {
        for (int j = 0; j < 1000; j++) {
            String s = (String) smap.get("" + j);
            max = s.length() > max.length() ? s : max;
        }
    }
    String2.log("test synchronized hashMap finished longest=" + max + " time="
            + (System.currentTimeMillis() - time) + "ms"); //343     

    //***
    String2.log("testConcurrentHashMap");
    time = System.currentTimeMillis();
    ConcurrentHashMap map = new ConcurrentHashMap(16, 0.75f, 4); //intentionally low initCapacity
    for (int i = 0; i < 1000; i++) {
        String s = "" + i;
        map.put(s, s);
    }
    max = "";
    for (int i = 0; i < 1000; i++) {
        for (int j = 0; j < 1000; j++) {
            String s = (String) map.get("" + j);
            max = s.length() > max.length() ? s : max;
        }
    }
    String2.log("testConcurrentHashMap finished longest=" + max + " time=" + (System.currentTimeMillis() - time)
            + "ms"); //282
}

From source file:org.apache.hadoop.hive.metastore.ObjectStore.java

private static long clearFieldMap(ClassLoaderResolverImpl clri, String mapFieldName) throws Exception {
    Field mapField = ClassLoaderResolverImpl.class.getDeclaredField(mapFieldName);
    mapField.setAccessible(true);//w  w  w. j a  v a  2 s  .  c om

    Map<String, Class> map = (Map<String, Class>) mapField.get(clri);
    long sz = map.size();
    mapField.set(clri, Collections.synchronizedMap(new WeakValueMap()));
    return sz;
}