List of usage examples for java.util Collections synchronizedMap
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
From source file:org.nuxeo.connect.packages.PackageManagerImpl.java
/** * Sort the given orderedList list of package ids by dependencies and optional dependencies. If a package A has a * dependency on a package B, B will be ordered before A. If B is missing, a {@link DependencyException} will be * thrown. If a package C has an optional dependency on a package D, D will be ordered before C. If D is missing, a * message will be logged to inform that D will be ignored. * * @param allPackagesByID all available packages sorted by id * @param listToOrder the package ids list to order * @param orderedRemoveList the package ids list which are going to be removed * @param isRemoveList if true, no message will be logged for missing optional dependencies * @throws DependencyException if one ore more dependency (non optional) is missing *//*from ww w. j a v a 2s .c o m*/ private void orderByDependencies(Map<String, DownloadablePackage> allPackagesByID, List<String> listToOrder, List<String> orderedRemoveList, boolean isRemoveList) throws DependencyException { Map<String, Package> orderedMap = Collections.synchronizedMap(new LinkedHashMap<String, Package>()); boolean hasChanged = true; Set<String> missingDeps = new HashSet<>(); Map<String, Set<String>> optionalMissingDeps = new HashMap<>(); while (!listToOrder.isEmpty() && hasChanged) { hasChanged = false; for (String id : listToOrder) { DownloadablePackage pkg = allPackagesByID.get(id); if (pkg.getDependencies().length == 0 && pkg.getOptionalDependencies().length == 0) { // Add pkg to orderedMap if it has no dependencies nor optional dependencies orderedMap.put(id, pkg); hasChanged = true; } else { // Add to orderedMap if all its dependencies and optional dependencies are satisfied boolean allSatisfied = true; List<PackageDependency> allDependencies = new ArrayList<>(); CollectionUtils.addAll(allDependencies, pkg.getDependencies()); List<PackageDependency> optionalDependencies = Arrays.asList(pkg.getOptionalDependencies()); allDependencies.addAll(optionalDependencies); for (PackageDependency pkgDep : allDependencies) { // is pkDep optional? boolean isOptionalPkgDep = optionalDependencies.contains(pkgDep); // is pkgDep satisfied in orderedMap? boolean satisfied = false; for (Package orderedPkg : orderedMap.values()) { if (matchDependency(pkgDep, orderedPkg)) { satisfied = true; if (isOptionalPkgDep) { if (optionalMissingDeps.get(id) != null) { optionalMissingDeps.get(id).remove(pkgDep.toString()); } } else { missingDeps.remove(pkgDep.toString()); } break; } } // else, is pkgDep satisfied in already installed pkgs and is not going to be removed or // upgraded ? if (!satisfied && !hasMatchInIdList(pkgDep, listToOrder)) { for (Version version : findLocalPackageInstalledVersions(pkgDep.getName())) { if ((isRemoveList || !hasMatchInIdList(pkgDep.getName(), version, orderedRemoveList)) && pkgDep.getVersionRange().matchVersion(version)) { satisfied = true; if (isOptionalPkgDep) { if (optionalMissingDeps.get(id) != null) { optionalMissingDeps.get(id).remove(pkgDep.toString()); } } else { missingDeps.remove(pkgDep.toString()); } break; } } // if it's an optional dependency that will not be installed if (!satisfied && isOptionalPkgDep) { // consider the pkDep as satisfied, but add it in optional missing dependencies for // logging if it is not going to be removed satisfied = true; if (!hasMatchInIdList(pkgDep, orderedRemoveList)) { optionalMissingDeps.computeIfAbsent(id, k -> new HashSet<>()) .add(pkgDep.toString()); } } } if (!satisfied) { // couldn't satisfy pkgDep allSatisfied = false; if (isOptionalPkgDep) { optionalMissingDeps.computeIfAbsent(id, k -> new HashSet<>()) .add(pkgDep.toString()); } else { missingDeps.add(pkgDep.toString()); } break; } } if (allSatisfied) { orderedMap.put(id, pkg); orderedRemoveList.remove(pkg.getName()); hasChanged = true; } } } listToOrder.removeAll(orderedMap.keySet()); } if (!optionalMissingDeps.isEmpty() && !isRemoveList) { for (Entry<String, Set<String>> entry : optionalMissingDeps.entrySet()) { if (entry.getValue() != null && !entry.getValue().isEmpty()) { log.info(String.format("Optional dependencies %s will be ignored for '%s'.", entry.getValue(), entry.getKey())); } } } if (!listToOrder.isEmpty()) { if (missingDeps.isEmpty()) { for (String id : listToOrder) { DownloadablePackage pkg = allPackagesByID.get(id); orderedMap.put(id, pkg); } listToOrder.clear(); } else { throw new DependencyException( String.format("Couldn't order %s missing %s.", listToOrder, missingDeps)); } } listToOrder.addAll(orderedMap.keySet()); }
From source file:de.fu_berlin.inf.dpp.net.internal.XMPPTransmitter.java
protected void prepareConnection(final XMPPConnection connection) { // Create Containers this.chats = new HashMap<JID, Chat>(); this.processes = Collections.synchronizedMap(new HashMap<JID, InvitationProcess>()); this.messageTransferQueue = Collections.synchronizedList(new LinkedList<MessageTransfer>()); this.connection = connection; this.chatmanager = connection.getChatManager(); // Register a PacketListener which takes care of decoupling the // processing of Packets from the Smack thread this.connection.addPacketListener(new PacketListener() { protected PacketFilter sessionFilter = PacketExtensionUtils.getSessionIDPacketFilter(sessionID); public void processPacket(final Packet packet) { dispatchThread.executeAsDispatch(new Runnable() { public void run() { if (sessionFilter.accept(packet)) { try { Message message = (Message) packet; JID fromJID = new JID(message.getFrom()); // Change the input method to get the right // chats putIncomingChat(fromJID, message.getThread()); } catch (Exception e) { log.error("An internal error occurred " + "while processing packets", e); }// w ww. j a v a 2 s.co m } receiver.processPacket(packet); } }); } }, null); }
From source file:org.dihedron.webmvc.ActionContext.java
/** * Sets the value associated with the given name into the given scope; * despite making no difference between parameters and attributes from a * theoretical standpoint, this method will actually perform a check to see * if an attempt is being made to store a value in a read-only context, so * make sure you do not try to set a value in FORM or CONFIGURATION scopes * as this would result in an error at runtime. * /*from w ww. j a v a2s . c o m*/ * @param key * the name of the value. * @param value * the value to be stored. * @param scope * the scope into which the value should be stored. */ @SuppressWarnings("unchecked") public static void setValue(String key, Object value, Scope scope) throws WebMVCException { if (!Strings.isValid(key)) { logger.error("value name must be valid"); throw new WebMVCException("Value name must be valid."); } if (scope.isReadOnly()) { logger.error("trying to store value in read-only scope '{}'", scope.name()); throw new WebMVCException("Trying to store value in read-only scope '" + scope.name() + "'."); } Map<String, Object> map = null; switch (scope) { case REQUEST: getContext().request.setAttribute(key, value); break; case CONVERSATION: String conversationId = Conversation.getConversationId(key); String valueId = Conversation.getValueId(key); if (Strings.areValid(conversationId, valueId)) { logger.trace("setting value '{}' in conversation '{}'", valueId, conversationId); synchronized (ActionContext.class) { Map<String, Map<String, Object>> conversations = (Map<String, Map<String, Object>>) getValue( CONVERSATION_SCOPED_ATTRIBUTES_KEY, Scope.SESSION); if (conversations == null) { conversations = Collections.synchronizedMap(new HashMap<String, Map<String, Object>>()); setValue(CONVERSATION_SCOPED_ATTRIBUTES_KEY, conversations, Scope.SESSION); } map = conversations.get(conversationId); if (map == null) { map = new HashMap<>(); conversations.put(conversationId, map); } map.put(valueId, value); } } break; case SESSION: getContext().request.getSession().setAttribute(key, value); break; case STICKY: String user = getRemoteUser(); if (Strings.isValid(user)) { user = user.trim(); synchronized (ActionContext.class) { Map<String, Map<String, Object>> sticky = (Map<String, Map<String, Object>>) getValue( STICKY_SCOPED_ATTRIBUTES_KEY, Scope.APPLICATION); if (sticky == null) { sticky = Collections.synchronizedMap(new HashMap<String, Map<String, Object>>()); setValue(STICKY_SCOPED_ATTRIBUTES_KEY, sticky, Scope.APPLICATION); } map = sticky.get(user); if (map == null) { map = new HashMap<>(); sticky.put(user, map); } map.put(key, value); } } break; case APPLICATION: getContext().filter.getServletContext().setAttribute(key, value); break; default: logger.error("should never get here: is this a bug?"); } logger.debug("value '{}' in scope '{}' set to value '{}' (class {})", key, scope.name(), value, value != null ? value.getClass().getSimpleName() : "n.a."); }
From source file:conf.Configuration.java
/** * Load a class by name./*from w w w . ja va2 s .c om*/ * * @param name the class name. * @return the class object. * @throws ClassNotFoundException if the class is not found. */ public Class<?> getClassByName(String name) throws ClassNotFoundException { Map<String, Class<?>> map; synchronized (CACHE_CLASSES) { map = CACHE_CLASSES.get(classLoader); if (map == null) { map = Collections.synchronizedMap(new WeakHashMap<String, Class<?>>()); CACHE_CLASSES.put(classLoader, map); } } Class clazz = map.get(name); if (clazz == null) { clazz = Class.forName(name, true, classLoader); if (clazz != null) { // two putters can race here, but they'll put the same class map.put(name, clazz); } } return clazz; }
From source file:aarddict.android.ArticleViewActivity.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override/* w ww. j a va 2 s. co m*/ protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); backItems = Collections.synchronizedList((List) savedInstanceState.getSerializable("backItems")); scrollPositionsH = Collections .synchronizedMap((Map) savedInstanceState.getSerializable("scrollPositionsH")); scrollPositionsV = Collections .synchronizedMap((Map) savedInstanceState.getSerializable("scrollPositionsV")); }
From source file:org.sakaiproject.sitestats.impl.StatsUpdateManagerImpl.java
@SuppressWarnings("unchecked") private synchronized boolean doUpdateConsolidatedEvents() { long startTime = System.currentTimeMillis(); if (eventStatMap.size() > 0 || resourceStatMap.size() > 0 || activityMap.size() > 0 || uniqueVisitsMap.size() > 0 || visitsMap.size() > 0 || presencesMap.size() > 0 || serverStatMap.size() > 0 || userStatMap.size() > 0) { Object r = getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Transaction tx = null;/* www . jav a 2 s. co m*/ try { tx = session.beginTransaction(); // do: EventStat if (eventStatMap.size() > 0) { Collection<EventStat> tmp1 = null; synchronized (eventStatMap) { tmp1 = eventStatMap.values(); eventStatMap = Collections.synchronizedMap(new HashMap<String, EventStat>()); } doUpdateEventStatObjects(session, tmp1); } // do: ResourceStat if (resourceStatMap.size() > 0) { Collection<ResourceStat> tmp2 = null; synchronized (resourceStatMap) { tmp2 = resourceStatMap.values(); resourceStatMap = Collections.synchronizedMap(new HashMap<String, ResourceStat>()); } doUpdateResourceStatObjects(session, tmp2); } // do: Lessons ResourceStat if (lessonBuilderStatMap.size() > 0) { Collection<LessonBuilderStat> tmp3 = null; synchronized (lessonBuilderStatMap) { tmp3 = lessonBuilderStatMap.values(); lessonBuilderStatMap = Collections .synchronizedMap(new HashMap<String, LessonBuilderStat>()); } doUpdateLessonBuilderStatObjects(session, tmp3); } // do: SiteActivity if (activityMap.size() > 0) { Collection<SiteActivity> tmp3 = null; synchronized (activityMap) { tmp3 = activityMap.values(); activityMap = Collections.synchronizedMap(new HashMap<String, SiteActivity>()); } doUpdateSiteActivityObjects(session, tmp3); } // do: SiteVisits if (uniqueVisitsMap.size() > 0 || visitsMap.size() > 0) { // determine unique visits for event related sites Map<UniqueVisitsKey, Integer> tmp4; synchronized (uniqueVisitsMap) { tmp4 = uniqueVisitsMap; uniqueVisitsMap = Collections .synchronizedMap(new HashMap<UniqueVisitsKey, Integer>()); } tmp4 = doGetSiteUniqueVisits(session, tmp4); // do: SiteVisits if (visitsMap.size() > 0) { Collection<SiteVisits> tmp5 = null; synchronized (visitsMap) { tmp5 = visitsMap.values(); visitsMap = Collections.synchronizedMap(new HashMap<String, SiteVisits>()); } doUpdateSiteVisitsObjects(session, tmp5, tmp4); } } // do: SitePresences if (presencesMap.size() > 0) { Collection<SitePresenceConsolidation> tmp6 = null; synchronized (presencesMap) { tmp6 = presencesMap.values(); presencesMap = Collections .synchronizedMap(new HashMap<String, SitePresenceConsolidation>()); } doUpdateSitePresencesObjects(session, tmp6); } // do: ServerStats if (serverStatMap.size() > 0) { Collection<ServerStat> tmp7 = null; synchronized (serverStatMap) { tmp7 = serverStatMap.values(); serverStatMap = Collections.synchronizedMap(new HashMap<String, ServerStat>()); } doUpdateServerStatObjects(session, tmp7); } // do: UserStats if (userStatMap.size() > 0) { Collection<UserStat> tmp8 = null; synchronized (userStatMap) { tmp8 = userStatMap.values(); userStatMap = Collections.synchronizedMap(new HashMap<String, UserStat>()); } doUpdateUserStatObjects(session, tmp8); } // commit ALL tx.commit(); } catch (Exception e) { if (tx != null) tx.rollback(); LOG.warn("Unable to commit transaction: ", e); return Boolean.FALSE; } return Boolean.TRUE; } }); long endTime = System.currentTimeMillis(); LOG.debug("Time spent in doUpdateConsolidatedEvents(): " + (endTime - startTime) + " ms"); return ((Boolean) r).booleanValue(); } else { return true; } }
From source file:org.meveo.admin.action.BaseBean.java
/** * crm/customers//from w ww . j ava2s. c o m * * */ public boolean canUserUpdateEntity() { if (this.writeAccessMap == null) { writeAccessMap = Collections.synchronizedMap(new HashMap<String, Boolean>()); } ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); HttpServletRequest request = (HttpServletRequest) context.getRequest(); String requestURI = request.getRequestURI(); if (writeAccessMap.get(requestURI) == null) { boolean hasWriteAccess = false; try { hasWriteAccess = PagePermission.getInstance().hasWriteAccess(request, identity); } catch (BusinessException e) { log.error("Error encountered checking for write access to {}", requestURI, e); hasWriteAccess = false; } writeAccessMap.put(requestURI, hasWriteAccess); } return writeAccessMap.get(requestURI); }
From source file:org.apache.hadoop.hbase.client.crosssite.CrossSiteHTable.java
/** * {@inheritDoc}/*from w ww . jav a 2s . c o m*/ */ @Override public <T extends Service, R> Map<byte[], R> coprocessorService(Class<T> protocol, byte[] startKey, byte[] endKey, Call<T, R> callable) throws IOException, Throwable { final Map<byte[], R> results = Collections.synchronizedMap(new TreeMap<byte[], R>(Bytes.BYTES_COMPARATOR)); coprocessorService(protocol, startKey, endKey, callable, new Batch.Callback<R>() { public void update(byte[] region, byte[] row, R value) { results.put(region, value); } }); return results; }
From source file:org.apache.hadoop.hbase.client.crosssite.CrossSiteHTable.java
/** * {@inheritDoc}/*from www.j a v a 2s . com*/ */ @Override public <T extends Service, R> Map<byte[], R> coprocessorService(Class<T> protocol, byte[] startKey, byte[] endKey, String[] clusterNames, Call<T, R> callable) throws IOException, Throwable { final Map<byte[], R> results = Collections.synchronizedMap(new TreeMap<byte[], R>(Bytes.BYTES_COMPARATOR)); coprocessorService(protocol, startKey, endKey, clusterNames, callable, new Batch.Callback<R>() { public void update(byte[] region, byte[] row, R value) { results.put(region, value); } }); return results; }