com.google.common.collect.MapMaker Java Examples

The following examples show how to use com.google.common.collect.MapMaker. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProtoTypeAdapter.java    From gson with Apache License 2.0 6 votes vote down vote up
private static Method getCachedMethod(Class<?> clazz, String methodName,
    Class<?>... methodParamTypes) throws NoSuchMethodException {
  Map<Class<?>, Method> mapOfMethods = mapOfMapOfMethods.get(methodName);
  if (mapOfMethods == null) {
    mapOfMethods = new MapMaker().makeMap();
    Map<Class<?>, Method> previous =
        mapOfMapOfMethods.putIfAbsent(methodName, mapOfMethods);
    mapOfMethods = previous == null ? mapOfMethods : previous;
  }

  Method method = mapOfMethods.get(clazz);
  if (method == null) {
    method = clazz.getMethod(methodName, methodParamTypes);
    mapOfMethods.putIfAbsent(clazz, method);
    // NB: it doesn't matter which method we return in the event of a race.
  }
  return method;
}
 
Example #2
Source File: MemoryMetaManager.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
public void start() {
    super.start();

    batches = MigrateMap.makeComputingMap(new Function<ClientIdentity, MemoryClientIdentityBatch>() {

        public MemoryClientIdentityBatch apply(ClientIdentity clientIdentity) {
            return MemoryClientIdentityBatch.create(clientIdentity);
        }

    });

    cursors = new MapMaker().makeMap();

    destinations = MigrateMap.makeComputingMap(new Function<String, List<ClientIdentity>>() {

        public List<ClientIdentity> apply(String destination) {
            return Lists.newArrayList();
        }
    });
}
 
Example #3
Source File: ShopManager.java    From QuickShop-Reremake with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Adds a shop to the world. Does NOT require the chunk or world to be loaded Call shop.onLoad by
 * yourself
 *
 * @param world The name of the world
 * @param shop  The shop to add
 */
public void addShop(@NotNull String world, @NotNull Shop shop) {
    Map<ShopChunk, Map<Location, Shop>> inWorld = this.getShops().computeIfAbsent(world, k -> new MapMaker().initialCapacity(3).makeMap());
    // There's no world storage yet. We need to create that map.
    // Put it in the data universe
    // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT
    // location rounded to the nearest 16.
    int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0);
    int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0);
    // Get the chunk set from the world info
    ShopChunk shopChunk = new ShopChunk(world, x, z);
    Map<Location, Shop> inChunk = inWorld.computeIfAbsent(shopChunk, k -> new MapMaker().initialCapacity(1).makeMap());
    // That chunk data hasn't been created yet - Create it!
    // Put it in the world
    // Put the shop in its location in the chunk list.
    inChunk.put(shop.getLocation(), shop);
    // shop.onLoad();

}
 
Example #4
Source File: MetricsCache.java    From watcher with Apache License 2.0 6 votes vote down vote up
private static void init() {
	if (!init) {
		synchronized (MetricsCache.class) {
			if (!init) {
				cache = new MapMaker().concurrencyLevel(4).weakValues().makeMap();
				scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
					@Override
					public Thread newThread(Runnable r) {
						Thread thread = new Thread(r);
						thread.setDaemon(true);
						thread.setName("watcher-cache-evict-thread");
						return thread;
					}
				});
				scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
					@Override
					public void run() {
						INSTANCE.evict();
					}
				}, 1l, 1l, TimeUnit.SECONDS);
				init = true;
			}
		}
	}
}
 
Example #5
Source File: RomClientWeakRemoteObjects.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testWeakRefsMap() throws Exception {

  ConcurrentMap<String, Object> objects = new MapMaker().weakValues().makeMap();

  objects.put("xxx", new Object());

  if (null == objects.get("xxx")) {
    Assert.fail("Reference should NOT be null");
  }

  try {
    @SuppressWarnings("unused")
    Object[] ignored = new Object[(int) Runtime.getRuntime().maxMemory()];
  } catch (Throwable e) {
    // Ignore OME
  }

  if (null != objects.get("xxx")) {
    Assert.fail("Reference should be null");
  }
}
 
Example #6
Source File: MemoryMetaManager.java    From canal with Apache License 2.0 6 votes vote down vote up
public void start() {
    super.start();

    batches = MigrateMap.makeComputingMap(new Function<ClientIdentity, MemoryClientIdentityBatch>() {

        public MemoryClientIdentityBatch apply(ClientIdentity clientIdentity) {
            return MemoryClientIdentityBatch.create(clientIdentity);
        }

    });

    cursors = new MapMaker().makeMap();

    destinations = MigrateMap.makeComputingMap(new Function<String, List<ClientIdentity>>() {

        public List<ClientIdentity> apply(String destination) {
            return Lists.newArrayList();
        }
    });
}
 
Example #7
Source File: GuavaMapMakerUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenCreateCaches_thenCreated() {
    ConcurrentMap<User, Session> sessionCache = new MapMaker().makeMap();
    assertNotNull(sessionCache);

    ConcurrentMap<User, Profile> profileCache = new MapMaker().makeMap();
    assertNotNull(profileCache);

    User userA = new User(1, "UserA");

    sessionCache.put(userA, new Session(100));
    Assert.assertThat(sessionCache.size(), equalTo(1));

    profileCache.put(userA, new Profile(1000, "Personal"));
    Assert.assertThat(profileCache.size(), equalTo(1));
}
 
Example #8
Source File: BrowserUpProxyServer.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
@Override
public void addHeaders(Map<String, String> headers) {
    ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap();
    newHeaders.putAll(headers);

    this.additionalHeaders = newHeaders;
}
 
Example #9
Source File: RebuildBreakdownServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init() {
    log.info("INIT: session clustering=" + isSessionClusteringEnabled());
    if (isSessionClusteringEnabled()) {
        sessionCache = memoryService.newCache("org.sakaiproject.tool.impl.RebuildBreakdownService.cache");

        stashingCache = memoryService.newCache("org.sakaiproject.tool.impl.RebuildBreakdownService.stash");

        sessionClassWhitelist = new HashSet<String>(4); // number should match items count below
        sessionClassWhitelist.add(Locale.class.getName());
        sessionClassWhitelist.add("org.sakaiproject.event.api.SimpleEvent");
        sessionClassWhitelist.add("org.sakaiproject.authz.api.SimpleRole");
        sessionClassWhitelist.add("org.apache.commons.lang.mutable.MutableLong");

        sessionAttributeBlacklist = new HashSet<String>(6); // number should match items count below
        sessionAttributeBlacklist.add(SESSION_LAST_BREAKDOWN_KEY);
        sessionAttributeBlacklist.add(SESSION_LAST_REBUILD_KEY);
        /* from BasePreferencesService.ATTR_PREFERENCE_IS_NULL
         * This controls whether the session cached version of prefs is reloaded or assumed to be populated,
         * when it is true the processing assumes it is populated (very weird logic and dual-caching)
         */
        sessionAttributeBlacklist.add("attr_preference_is_null");
        /* from BasePreferencesService.ATTR_PREFERENCE
         * rebuild this manually on demand from the cache instead of storing it
         */
        sessionAttributeBlacklist.add("attr_preference");
        /** should be re-detected on rebuild of the session */
        sessionAttributeBlacklist.add("is_mobile_device");
        /** this is normally only set on login, we handle it specially on breakdown and rebuild */
        sessionAttributeBlacklist.add(UsageSessionService.USAGE_SESSION_KEY);
    }
    /* Create a map with weak references to the values */
    breakdownableHandlers = new MapMaker().weakValues().makeMap();
}
 
Example #10
Source File: MapMakerT0.java    From java-core-learning-example with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    /**
     * expiration(3, TimeUnit.SECONDS)设置超时时间为3秒
     */
    ConcurrentMap<String , String> map = new MapMaker().concurrencyLevel(32).softKeys().weakValues()
            .expiration(3, TimeUnit.SECONDS).makeComputingMap(
                    /**
                     * 提供当Map里面不包含所get的项,可以自动加入到Map的功能
                     * 可以将这里的返回值放到对应的key的value中
                     */
                    new Function<String, String>() {
                        public String apply(String s) {
                            return "creating " + s + " -> Object";
                        }
                    }
            );

    map.put("a","testa");
    map.put("b","testb");

    System.out.println(map.get("a"));
    System.out.println(map.get("b"));
    System.out.println(map.get("c"));

    try {
        // 4秒后,大于超时时间,缓存失效。
        Thread.sleep(4000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(map.get("a"));
    System.out.println(map.get("b"));
    System.out.println(map.get("c"));
}
 
Example #11
Source File: BrowserMobProxyServer.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public void addHeaders(Map<String, String> headers) {
    ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap();
    newHeaders.putAll(headers);

    this.additionalHeaders = newHeaders;
}
 
Example #12
Source File: BrowserMobProxyServer.java    From Dream-Catcher with MIT License 5 votes vote down vote up
@Override
public void addHeaders(Map<String, String> headers) {
    ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap();
    newHeaders.putAll(headers);

    this.additionalHeaders = newHeaders;
}
 
Example #13
Source File: RebuildBreakdownServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init() {
    log.info("INIT: session clustering=" + isSessionClusteringEnabled());
    if (isSessionClusteringEnabled()) {
        sessionCache = memoryService.newCache("org.sakaiproject.tool.impl.RebuildBreakdownService.cache");

        stashingCache = memoryService.newCache("org.sakaiproject.tool.impl.RebuildBreakdownService.stash");

        sessionClassWhitelist = new HashSet<String>(4); // number should match items count below
        sessionClassWhitelist.add(Locale.class.getName());
        sessionClassWhitelist.add("org.sakaiproject.event.api.SimpleEvent");
        sessionClassWhitelist.add("org.sakaiproject.authz.api.SimpleRole");
        sessionClassWhitelist.add("org.apache.commons.lang.mutable.MutableLong");

        sessionAttributeBlacklist = new HashSet<String>(6); // number should match items count below
        sessionAttributeBlacklist.add(SESSION_LAST_BREAKDOWN_KEY);
        sessionAttributeBlacklist.add(SESSION_LAST_REBUILD_KEY);
        /* from BasePreferencesService.ATTR_PREFERENCE_IS_NULL
         * This controls whether the session cached version of prefs is reloaded or assumed to be populated,
         * when it is true the processing assumes it is populated (very weird logic and dual-caching)
         */
        sessionAttributeBlacklist.add("attr_preference_is_null");
        /* from BasePreferencesService.ATTR_PREFERENCE
         * rebuild this manually on demand from the cache instead of storing it
         */
        sessionAttributeBlacklist.add("attr_preference");
        /** should be re-detected on rebuild of the session */
        sessionAttributeBlacklist.add("is_mobile_device");
        /** this is normally only set on login, we handle it specially on breakdown and rebuild */
        sessionAttributeBlacklist.add(UsageSessionService.USAGE_SESSION_KEY);
    }
    /* Create a map with weak references to the values */
    breakdownableHandlers = new MapMaker().weakValues().makeMap();
}
 
Example #14
Source File: ConcurrentHashSet.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new, empty ConcurrentHashSet. 
 */
public ConcurrentHashSet() {
	// had some really weird NPEs with Java's ConcurrentHashMap (i.e. got a
	// NPE at size()), now trying witrh Guava instead
    delegate = new MapMaker().concurrencyLevel
    		(Runtime.getRuntime().availableProcessors()).makeMap();
}
 
Example #15
Source File: BrowserMobProxyServer.java    From CapturePacket with MIT License 5 votes vote down vote up
@Override
public void addHeaders(Map<String, String> headers) {
    ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap();
    newHeaders.putAll(headers);

    this.additionalHeaders = newHeaders;
}
 
Example #16
Source File: DalvikStatsCache.java    From buck with Apache License 2.0 4 votes vote down vote up
DalvikStatsCache() {
  cache = new MapMaker().weakKeys().makeMap();
}
 
Example #17
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 4 votes vote down vote up
ComputingMapSupplier(Supplier<MapMaker> mapMakerSupplier) {
  this.mapMakerSupplier = mapMakerSupplier;
}
 
Example #18
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 4 votes vote down vote up
ComputingMapSupplier(Supplier<MapMaker> mapMakerSupplier) {
  this.mapMakerSupplier = mapMakerSupplier;
}
 
Example #19
Source File: DefaultSessionManager.java    From bistoury with GNU General Public License v3.0 4 votes vote down vote up
private <T> Set<T> createRelativeSet() {
    ConcurrentMap<T, Boolean> map = new MapMaker().weakKeys().makeMap();
    return Sets.newSetFromMap(map);
}
 
Example #20
Source File: SugarContext.java    From ApkTrack with GNU General Public License v3.0 4 votes vote down vote up
private SugarContext(Context context) {
    this.context = context;
    this.sugarDb = new SugarDb(context);
    this.entitiesMap = new MapMaker().weakKeys().makeMap();
}
 
Example #21
Source File: AbstractUaNodeManager.java    From ua-server-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
public AbstractUaNodeManager() {
    MapMaker mapMaker = new MapMaker();

    nodeMap = makeNodeMap(mapMaker);
}
 
Example #22
Source File: AbstractUaNodeManager.java    From ua-server-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
protected ConcurrentMap<NodeId, UaNode> makeNodeMap(MapMaker mapMaker) {
    return mapMaker.makeMap();
}
 
Example #23
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 4 votes vote down vote up
MapSupplier(Supplier<MapMaker> mapMakerSupplier) {
  this.mapMakerSupplier = mapMakerSupplier;
}
 
Example #24
Source File: WorldRetrogen.java    From simpleretrogen with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void serverAboutToStart(FMLServerAboutToStartEvent evt)
{
    this.pendingWork = new MapMaker().weakKeys().makeMap();
    this.completedWork = new MapMaker().weakKeys().makeMap();
    this.completedWorkLocks = new MapMaker().weakKeys().makeMap();

    Set<IWorldGenerator> worldGens = ObfuscationReflectionHelper.getPrivateValue(GameRegistry.class, null, "worldGenerators");
    Map<IWorldGenerator,Integer> worldGenIdx = ObfuscationReflectionHelper.getPrivateValue(GameRegistry.class, null, "worldGeneratorIndex");

    for (String retro : ImmutableSet.copyOf(retros.keySet()))
    {
        if (!delegates.containsKey(retro))
        {
            FMLLog.info("Substituting worldgenerator %s with delegate", retro);
            for (Iterator<IWorldGenerator> iterator = worldGens.iterator(); iterator.hasNext();)
            {
                IWorldGenerator wg = iterator.next();
                if (wg.getClass().getName().equals(retro))
                {
                    iterator.remove();
                    TargetWorldWrapper tww = new TargetWorldWrapper();
                    tww.delegate = wg;
                    tww.tag = retro;
                    worldGens.add(tww);
                    Integer idx = worldGenIdx.remove(wg);
                    worldGenIdx.put(tww, idx);
                    FMLLog.info("Successfully substituted %s with delegate", retro);
                    delegates.put(retro, tww);
                    break;
                }
            }

            if (!delegates.containsKey(retro))
            {
                FMLLog.warning("WorldRetrogen was not able to locate world generator class %s, it will be skipped, found %s", retro, worldGens);
                retros.remove(retro);
            }
        }
    }
}
 
Example #25
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 4 votes vote down vote up
private static void analyzeMapMaker(String caption, Supplier<MapMaker> supplier) {
  analyze(caption, new MapPopulator(new MapSupplier(supplier)));
  analyze(caption + "_Computing", new MapPopulator(new ComputingMapSupplier(supplier)));
}
 
Example #26
Source File: GuavaMapMakerUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenCreateCacheWithInitialCapacity_thenCreated() {
    ConcurrentMap<User, Profile> profileCache = new MapMaker().initialCapacity(100).makeMap();
    assertNotNull(profileCache);
}
 
Example #27
Source File: Beans.java    From glowroot with Apache License 2.0 4 votes vote down vote up
@Override
public ConcurrentMap<String, Accessor> load(Class<?> clazz) {
    // weak values since Method has a strong reference to its Class which
    // is used as the key in the outer loading cache
    return new MapMaker().weakValues().makeMap();
}
 
Example #28
Source File: MemoryLogPositionManager.java    From canal with Apache License 2.0 4 votes vote down vote up
@Override
public void start() {
    super.start();
    positions = new MapMaker().makeMap();
}
 
Example #29
Source File: BitSetDocumentVisibilityFilterCacheStrategy.java    From incubator-retired-blur with Apache License 2.0 4 votes vote down vote up
public BitSetDocumentVisibilityFilterCacheStrategy() {
  _cache = new MapMaker().makeMap();
}
 
Example #30
Source File: Maps.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private static MapMaker createWeakMapMaker() {
    final MapMaker mapMaker = new MapMaker();
    mapMaker.weakKeys();
    return mapMaker;
}