List of usage examples for com.google.common.collect MapMaker MapMaker
public MapMaker()
From source file:me.schiz.jmeter.ring.tcp.Ring.java
public Ring init() { //hashedWheelTimer = new HashedWheelTimer(); //hashedWheelTimer.start(); for (int i = 0; i < hashedWheelTimers.length; i++) { hashedWheelTimers[i] = new HashedWheelTimer(); hashedWheelTimers[i].start();/* w ww .jav a2s . c o m*/ } for (int i = 0; i < selectorsCount; i++) { try { selectors[i] = Selector.open(); } catch (IOException e) { log.error("can't open selector ", e); } } for (int i = 0; i < selectorsCount; ++i) { eventLoopRunnables[i] = new EventLoopRunnable(this, selectors[i]); threads[i] = new Thread(eventLoopRunnables[i]); threads[i].setDaemon(true); threads[i].setName("EventLoopThread#" + i); threads[i].start(); } weakSocketToTokenMap = new MapMaker().concurrencyLevel(Runtime.getRuntime().availableProcessors()) .initialCapacity(socketsCount).softKeys().makeMap(); for (int i = 0; i < socketsCount; i++) { String[] addr; String host = "localhost"; int port; try { addr = addrs[i % addrs.length].split(":"); host = addr[0]; port = Integer.parseInt(addr[1]); } catch (PatternSyntaxException | NumberFormatException e) { log.error("bad address \"" + addrs[i % addrs.length] + "\"", e); return this; } try { Token t = ring.get(i); t.id = i; t.targetAddress = new InetSocketAddress(host, port); setSocketOptions(t.socketChannel); try { eventLoopRunnables[i % selectorsCount].register(t.socketChannel, SelectionKey.OP_CONNECT | SelectionKey.OP_READ); } catch (InterruptedException e) { log.error("InterruptedException when register SocketChannel", e); break; } ring.get(i).connectStartTS = System.nanoTime(); ring.get(i).socketChannel.connect(ring.get(i).targetAddress); ring.get(i).timeout = hashedWheelTimers[i % hashedWheelTimers.length] .newTimeout(new TimeoutTask(this, i, "connect"), connectTimeout, TimeUnit.MILLISECONDS); weakSocketToTokenMap.putIfAbsent(t.socketChannel, t); } catch (IOException e) { log.error("IOException ", e); } } schedEx.scheduleWithFixedDelay(new RingInfoRunnable(this), 0, 1000, TimeUnit.MILLISECONDS); return this; }
From source file:com.alibaba.otter.node.etl.common.db.dialect.AbstractDbDialect.java
private void initTables(final JdbcTemplate jdbcTemplate) { // soft??/* w w w .j av a2 s .co m*/ GenericMapMaker mapMaker = null; mapMaker = new MapMaker().softValues().evictionListener(new MapEvictionListener<List<String>, Table>() { public void onEviction(List<String> names, Table table) { logger.warn("Eviction For Table:" + table); } }); this.tables = mapMaker.makeComputingMap(new Function<List<String>, Table>() { public Table apply(List<String> names) { Assert.isTrue(names.size() == 2); try { beforeFindTable(jdbcTemplate, names.get(0), names.get(0), names.get(1)); DdlUtilsFilter filter = getDdlUtilsFilter(jdbcTemplate, names.get(0), names.get(0), names.get(1)); Table table = DdlUtils.findTable(jdbcTemplate, names.get(0), names.get(0), names.get(1), filter); afterFindTable(table, jdbcTemplate, names.get(0), names.get(0), names.get(1)); if (table == null) { throw new NestableRuntimeException( "no found table [" + names.get(0) + "." + names.get(1) + "] , pls check"); } else { return table; } } catch (Exception e) { throw new NestableRuntimeException( "find table [" + names.get(0) + "." + names.get(1) + "] error", e); } } }); }
From source file:me.lucko.luckperms.sponge.service.LuckPermsService.java
public LuckPermsService(LPSpongePlugin plugin) { this.plugin = plugin; localPermissionCaches = Collections.newSetFromMap(new MapMaker().weakKeys().makeMap()); localParentCaches = Collections.newSetFromMap(new MapMaker().weakKeys().makeMap()); localOptionCaches = Collections.newSetFromMap(new MapMaker().weakKeys().makeMap()); localDataCaches = Collections.newSetFromMap(new MapMaker().weakKeys().makeMap()); storage = new SubjectStorage(new File(plugin.getDataDirectory(), "local")); userSubjects = plugin.getUserManager(); fallbackUserSubjects = new PersistedCollection(this, "fallback-users", true); groupSubjects = plugin.getGroupManager(); fallbackGroupSubjects = new PersistedCollection(this, "fallback-groups", true); defaultSubjects = new PersistedCollection(this, "defaults", false); defaultSubjects.loadAll();// w w w .j av a 2s . com collections.put(PermissionService.SUBJECTS_USER, userSubjects); collections.put("fallback-users", fallbackUserSubjects); collections.put(PermissionService.SUBJECTS_GROUP, groupSubjects); collections.put("fallback-groups", fallbackGroupSubjects); collections.put("defaults", defaultSubjects); for (String collection : storage.getSavedCollections()) { if (collections.asMap().containsKey(collection.toLowerCase())) { continue; } PersistedCollection c = new PersistedCollection(this, collection.toLowerCase(), true); c.loadAll(); collections.put(c.getIdentifier(), c); } descriptionSet = ConcurrentHashMap.newKeySet(); }
From source file:org.jasig.services.persondir.support.jdbc.MultiRowJdbcPersonAttributeDao.java
@Override @SuppressWarnings("unchecked") protected List<IPersonAttributes> parseAttributeMapFromResults(final List<Map<String, Object>> queryResults, final String queryUserName) { final Map<String, Map<String, List<Object>>> peopleAttributesBuilder = new MapMaker().makeMap(); final String userNameAttribute = this.getConfiguredUserNameAttribute(); for (final Map<String, Object> queryResult : queryResults) { final String userName; // Choose a username from the best available option if (this.isUserNameAttributeConfigured() && queryResult.containsKey(userNameAttribute)) { // Option #1: An attribute is named explicitly in the config, // and that attribute is present in the results from LDAP; use it final Object userNameValue = queryResult.get(userNameAttribute); userName = userNameValue.toString(); } else if (queryUserName != null) { // Option #2: Use the userName attribute provided in the query // parameters. (NB: I'm not entirely sure this choice is // preferable to Option #3. Keeping it because it most closely // matches the legacy behavior there the new option -- Option #1 // -- doesn't apply. ~drewwills) userName = queryUserName;/*from ww w . java 2 s. com*/ } else if (queryResult.containsKey(userNameAttribute)) { // Option #3: Create the IPersonAttributes useing the default // userName attribute, which we know to be present final Object userNameValue = queryResult.get(userNameAttribute); userName = userNameValue.toString(); } else { throw new BadSqlGrammarException( "No userName column named '" + userNameAttribute + "' exists in result set and no userName provided in query Map", this.getQueryTemplate(), null); } final Map<String, List<Object>> attributes = peopleAttributesBuilder.computeIfAbsent(userName, key -> new LinkedHashMap<String, List<Object>>()); //Iterate over each attribute column mapping to get the data from the row for (final Map.Entry<String, Set<String>> columnMapping : this.nameValueColumnMappings.entrySet()) { final String keyColumn = columnMapping.getKey(); //Get the attribute name for the specified column final Object attrNameObj = queryResult.get(keyColumn); if (attrNameObj == null && !queryResult.containsKey(keyColumn)) { throw new BadSqlGrammarException( "No attribute key column named '" + keyColumn + "' exists in result set", this.getQueryTemplate(), null); } final String attrName = String.valueOf(attrNameObj); //Get the columns containing the values and add all values to a List final Set<String> valueColumns = columnMapping.getValue(); final List<Object> attrValues = new ArrayList<>(valueColumns.size()); for (final String valueColumn : valueColumns) { final Object attrValue = queryResult.get(valueColumn); if (attrValue == null && !queryResult.containsKey(valueColumn)) { throw new BadSqlGrammarException( "No attribute value column named '" + valueColumn + "' exists in result set", this.getQueryTemplate(), null); } attrValues.add(attrValue); } //Add the name/values to the attributes Map MultivaluedPersonAttributeUtils.addResult(attributes, attrName, attrValues); } } //Convert the builder structure into a List of IPersons final List<IPersonAttributes> people = new ArrayList<>(peopleAttributesBuilder.size()); for (final Map.Entry<String, Map<String, List<Object>>> mappedAttributesEntry : peopleAttributesBuilder .entrySet()) { final String userName = mappedAttributesEntry.getKey(); final Map<String, List<Object>> attributes = mappedAttributesEntry.getValue(); // PERSONDIR-89, PERSONDIR-91 Should this be CaseInsensitiveNamedPersonImpl like SingleRowJdbcPersonAttribute? final IPersonAttributes person = new NamedPersonImpl(userName, attributes); people.add(person); } return people; }
From source file:com.palantir.common.concurrent.ExecutorInheritableThreadLocal.java
private static ConcurrentMap<ExecutorInheritableThreadLocal<?>, Object> makeNewMap() { return new MapMaker().weakKeys().concurrencyLevel(1).makeMap(); }
From source file:com.metamx.druid.curator.announcement.Announcer.java
/** * Announces the provided bytes at the given path. Announcement means that it will create an ephemeral node * and monitor it to make sure that it always exists until it is unannounced or this object is closed. * * @param path The path to announce at/* ww w .ja va 2s .c o m*/ * @param bytes The payload to announce */ public void announce(String path, byte[] bytes) { synchronized (toAnnounce) { if (!started) { toAnnounce.add(Pair.of(path, bytes)); return; } } final ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path); final String parentPath = pathAndNode.getPath(); boolean buildParentPath = false; ConcurrentMap<String, byte[]> subPaths = announcements.get(parentPath); if (subPaths == null) { try { if (curator.checkExists().forPath(parentPath) == null) { buildParentPath = true; } } catch (Exception e) { log.debug(e, "Problem checking if the parent existed, ignoring."); } // I don't have a watcher on this path yet, create a Map and start watching. announcements.putIfAbsent(parentPath, new MapMaker().<String, byte[]>makeMap()); // Guaranteed to be non-null, but might be a map put in there by another thread. final ConcurrentMap<String, byte[]> finalSubPaths = announcements.get(parentPath); // Synchronize to make sure that I only create a listener once. synchronized (finalSubPaths) { if (!listeners.containsKey(parentPath)) { final PathChildrenCache cache = factory.make(curator, parentPath); cache.getListenable().addListener(new PathChildrenCacheListener() { private final AtomicReference<Set<String>> pathsLost = new AtomicReference<Set<String>>( null); @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { log.debug("Path[%s] got event[%s]", parentPath, event); switch (event.getType()) { case CHILD_REMOVED: final ChildData child = event.getData(); final ZKPaths.PathAndNode childPath = ZKPaths.getPathAndNode(child.getPath()); final byte[] value = finalSubPaths.get(childPath.getNode()); if (value != null) { log.info("Node[%s] dropped, reinstating.", child.getPath()); createAnnouncement(child.getPath(), value); } break; case CONNECTION_LOST: // Lost connection, which means session is broken, take inventory of what has been seen. // This is to protect from a race condition in which the ephemeral node could have been // created but not actually seen by the PathChildrenCache, which means that it won't know // that it disappeared and thus will not generate a CHILD_REMOVED event for us. Under normal // circumstances, this can only happen upon connection loss; but technically if you have // an adversary in the system, they could also delete the ephemeral node before the cache sees // it. This does not protect from that case, so don't have adversaries. Set<String> pathsToReinstate = Sets.newHashSet(); for (String node : finalSubPaths.keySet()) { pathsToReinstate.add(ZKPaths.makePath(parentPath, node)); } for (ChildData data : cache.getCurrentData()) { pathsToReinstate.remove(data.getPath()); } if (!pathsToReinstate.isEmpty() && !pathsLost.compareAndSet(null, pathsToReinstate)) { log.info("Already had a pathsLost set!?[%s]", parentPath); } break; case CONNECTION_RECONNECTED: final Set<String> thePathsLost = pathsLost.getAndSet(null); if (thePathsLost != null) { for (String path : thePathsLost) { log.info("Reinstating [%s]", path); final ZKPaths.PathAndNode split = ZKPaths.getPathAndNode(path); createAnnouncement(path, announcements.get(split.getPath()).get(split.getNode())); } } break; } } }); synchronized (toAnnounce) { if (started) { if (buildParentPath) { createPath(parentPath); } startCache(cache); listeners.put(parentPath, cache); } } } } subPaths = finalSubPaths; } boolean created = false; synchronized (toAnnounce) { if (started) { byte[] oldBytes = subPaths.putIfAbsent(pathAndNode.getNode(), bytes); if (oldBytes == null) { created = true; } else if (!Arrays.equals(oldBytes, bytes)) { throw new IAE("Cannot reannounce different values under the same path"); } } } if (created) { try { createAnnouncement(path, bytes); } catch (Exception e) { throw Throwables.propagate(e); } } }
From source file:org.artifactory.storage.db.binstore.service.BinaryStoreImpl.java
@PostConstruct public void initialize() { try {// www.jav a 2s . c om garbageCollectorListeners = new CopyOnWriteArrayList<>(); binaryProvidersMap = loadProvidersMap(); log.debug("Initializing the ConfigurableBinaryProviderManager"); deleteProtectedBinaries = new MapMaker().makeMap(); File haAwareEtcDir = ArtifactoryHome.get().getHaAwareEtcDir(); ChainMetaData selectedChain; // If the new generation binary config exist the use it else use the old generation filestore File userConfigFile = new File(haAwareEtcDir, "binarystore.xml"); if (userConfigFile.exists()) { // Create binary provider according to the The new generation config selectedChain = buildByConfig(userConfigFile); } else { // Create binary provider using to the The old generation properties selectedChain = buildByStorageProperties(storageProperties); } // Now that we have the chain create the binary providers firstBinaryProvider = (UsageTrackingBinaryProvider) buildProviders(selectedChain, this, storageProperties); fileBinaryProvider = searchForFileBinaryProvider(firstBinaryProvider); // Add External binary providers String mode = storageProperties.getBinaryProviderExternalMode(); String externalDir = storageProperties.getBinaryProviderExternalDir(); addBinaryProvider( createExternalBinaryProviders(mode, externalDir, fileBinaryProvider, storageProperties, this)); } catch (IOException e) { throw new RuntimeException( "Failed to initialize binary providers. Reason io exception occurred during the config read process"); } }
From source file:com.noxpvp.mmo.util.PlayerClassUtil.java
public static void init() { log = NoxMMO.getInstance().getModuleLogger(LOG_MODULE_NAME); classIdNameMap = new DualAccessMap<String, String>(); pClasses = new DualAccessMap<String, Class<? extends PlayerClass>>(); classCache = new MapMaker().weakValues().concurrencyLevel(2).makeMap(); }
From source file:org.apache.giraph.comm.messages.with_source.ByteArrayMessagesPerSourceVertexStore.java
/** * Get the source map for a destination vertex id from the iterator, creating * if necessary. This method will take ownership of the vertex id from the * iterator if necessary (if used in the partition map entry). * * @param partitionMap Partition map to look in * @param iterator Special iterator that can release ownerships of vertex ids * @return Source map for this destination vertex id (created if necessary) *///www . ja va2s . c o m private ConcurrentMap<I, DataInputOutput> getOrCreateSourceMap( ConcurrentMap<I, ConcurrentMap<I, DataInputOutput>> partitionMap, VertexIdIterator<I> iterator) { ConcurrentMap<I, DataInputOutput> srcMap = partitionMap.get(iterator.getCurrentVertexId()); if (srcMap == null) { ConcurrentMap<I, DataInputOutput> tmpMap = new MapMaker() .concurrencyLevel(config.getNettyServerExecutionConcurrency()).makeMap(); srcMap = partitionMap.putIfAbsent(iterator.releaseCurrentVertexId(), tmpMap); if (srcMap == null) { srcMap = tmpMap; } } return srcMap; }
From source file:org.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl.java
public void activate(ComponentContext cc) { emf = persistenceProvider.createEntityManagerFactory( "org.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl", persistenceProperties); // Setup the agent cache agentCache = new MapMaker().expireAfterWrite(1, TimeUnit.HOURS) .makeComputingMap(new Function<String, Object>() { public Object apply(String id) { String[] key = id.split(DELIMITER); AgentImpl agent;//from ww w . jav a2 s . c om try { agent = getAgent(key[0], key[1]); } catch (NotFoundException e) { return nullToken; } return agent == null ? nullToken : Tuple.tuple(agent.getState(), agent.getConfiguration()); } }); }