Example usage for com.google.common.collect MapMaker MapMaker

List of usage examples for com.google.common.collect MapMaker MapMaker

Introduction

In this page you can find the example usage for com.google.common.collect MapMaker MapMaker.

Prototype

public MapMaker() 

Source Link

Usage

From source file:org.apache.blur.server.cache.ThriftCache.java

public ThriftCache(long totalNumberOfBytes) {
    _attributeKeys = new MapMaker().weakKeys().makeMap();
    _shardsKeys = new MapMaker().weakKeys().makeMap();
    _hits = Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, THRIFT_CACHE, HIT), HIT, TimeUnit.SECONDS);
    _misses = Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, THRIFT_CACHE, MISS), MISS, TimeUnit.SECONDS);
    _evictions = Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, THRIFT_CACHE, EVICTION), EVICTION,
            TimeUnit.SECONDS);//from  w w w. j a  va2  s.c o  m
    _cacheMap = new ConcurrentLinkedHashMap.Builder<ThriftCacheKey<?>, ThriftCacheValue<?>>()
            .weigher(new EntryWeigher<ThriftCacheKey<?>, ThriftCacheValue<?>>() {
                @Override
                public int weightOf(ThriftCacheKey<?> key, ThriftCacheValue<?> value) {
                    return key.size() + value.size();
                }
            }).listener(new EvictionListener<ThriftCacheKey<?>, ThriftCacheValue<?>>() {
                @Override
                public void onEviction(ThriftCacheKey<?> key, ThriftCacheValue<?> value) {
                    _evictions.mark();
                    _evictionsAtomicLong.incrementAndGet();
                }
            }).maximumWeightedCapacity(totalNumberOfBytes).build();
    _hitsAtomicLong = new AtomicLong();
    _missesAtomicLong = new AtomicLong();
    _evictionsAtomicLong = new AtomicLong();
    Metrics.newGauge(new MetricName(ORG_APACHE_BLUR, THRIFT_CACHE, SIZE), new Gauge<Long>() {
        @Override
        public Long value() {
            return _cacheMap.weightedSize();
        }
    });
    Metrics.newGauge(new MetricName(ORG_APACHE_BLUR, THRIFT_CACHE, COUNT), new Gauge<Long>() {
        @Override
        public Long value() {
            return (long) _cacheMap.size();
        }
    });
    Metrics.newGauge(new MetricName(ORG_APACHE_BLUR, THRIFT_CACHE_ATTRIBUTE_MAP, COUNT), new Gauge<Long>() {
        @Override
        public Long value() {
            return (long) _attributeKeys.size();
        }
    });
}

From source file:org.apache.flex.compiler.clients.problems.WorkspaceProblemFormatter.java

/**
 * Constructor./*from   w  ww  .ja  v  a2  s  . c  o  m*/
 * 
 * @param workspace workspace that contains files associated with specified 
 * problems.
 * @param problemCategorizer a class the categorizes problems into one of the
 * values in {@link CompilerProblemSeverity}. Adds "Error:" and "Warning:" into
 * the format of a problem. If null, the problem categories will not be added 
 * to the output. 
 */
public WorkspaceProblemFormatter(final Workspace workspace, CompilerProblemCategorizer problemCategorizer) {
    super();

    this.workspace = workspace;
    this.problemCategorizer = problemCategorizer;

    readers = new MapMaker().concurrencyLevel(1).softValues()
            .makeComputingMap(new Function<String, FileLineInfo>() {

                @Override
                public FileLineInfo apply(String fileName) {
                    return new FileLineInfo(fileName);
                }
            });
}

From source file:com.quinsoft.zeidon.standardoe.TaskImpl.java

TaskImpl(JavaObjectEngine objectEngine, Application app, String taskId) {
    super(app);/* ww w.  java2  s. c  o  m*/
    isValid = true;
    this.taskId = taskId;
    this.objectEngine = objectEngine;

    // Check to see if this is the system task.  It's ok to use '==' instead of .equals()
    // because we control the creation of the system task.
    isSystemTask = (taskId == ObjectEngine.ZEIDON_SYSTEM_APP_NAME);

    // viewList is a weak map.  This way we can get a list of views if necessary
    // (the browser needs this) but it won't hold onto views once they are no longer
    // in use.
    viewList = new MapMaker().concurrencyLevel(2).weakKeys().makeMap();
    viewNameList = new ViewNameList();
    description = this.taskId;

    String prefix = String.format(" [%4s] ", taskId);
    logger = new TaskLogger(prefix);
    dblogger = new TaskLogger(prefix);
    String logLevel = this.readZeidonConfig(app.getName(), "InitialLogLevel");
    if (!StringUtils.isBlank(logLevel)) {
        logger.setLevel(logLevel);
        dblogger.setLevel(logLevel);
    }

    log().info("Created new task for app %s, task ID = %s", app.getName(), taskId);
}

From source file:com.wareninja.opensource.droidfu.cachefu.AbstractCache.java

/**
 * Creates a new cache instance./*from   w  w w. j a  v a  2s. com*/
 * 
 * @param name
 *            a human readable identifier for this cache. Note that this value will be used to
 *            derive a directory name if the disk cache is enabled, so don't get too creative
 *            here (camel case names work great)
 * @param initialCapacity
 *            the initial element size of the cache
 * @param expirationInMinutes
 *            time in minutes after which elements will be purged from the cache (NOTE: this
 *            only affects the memory cache, the disk cache does currently NOT handle element
 *            TTLs!)
 * @param maxConcurrentThreads
 *            how many threads you think may at once access the cache; this need not be an exact
 *            number, but it helps in fragmenting the cache properly
 */
public AbstractCache(String name, int initialCapacity, long expirationInMinutes, int maxConcurrentThreads) {

    this.name = name;

    MapMaker mapMaker = new MapMaker();
    mapMaker.initialCapacity(initialCapacity);
    mapMaker.expiration(expirationInMinutes * 60, TimeUnit.SECONDS);
    mapMaker.concurrencyLevel(maxConcurrentThreads);
    mapMaker.softValues();
    this.cache = mapMaker.makeMap();
}

From source file:org.apache.giraph.edge.AbstractEdgeStore.java

/**
 * Constructor./*from   w  w w.ja  va2  s . co  m*/
 *
 * @param service Service worker
 * @param configuration Configuration
 * @param progressable Progressable
 */
public AbstractEdgeStore(CentralizedServiceWorker<I, V, E> service,
        ImmutableClassesGiraphConfiguration<I, V, E> configuration, Progressable progressable) {
    this.service = service;
    this.configuration = configuration;
    this.progressable = progressable;
    transientEdges = new MapMaker().concurrencyLevel(configuration.getNettyServerExecutionConcurrency())
            .makeMap();
    reuseEdgeObjects = configuration.reuseEdgeObjects();
    useInputOutEdges = configuration.useInputOutEdges();
}

From source file:org.apache.giraph.edge.EdgeStore.java

/**
 * Add edges belonging to a given partition on this worker.
 * Note: This method is thread-safe.//from   ww  w .  jav a  2 s  .  c o  m
 *
 * @param partitionId Partition id for the incoming edges.
 * @param edges Incoming edges
 */
public void addPartitionEdges(int partitionId, ByteArrayVertexIdEdges<I, E> edges) {
    ConcurrentMap<I, OutEdges<I, E>> partitionEdges = transientEdges.get(partitionId);
    if (partitionEdges == null) {
        ConcurrentMap<I, OutEdges<I, E>> newPartitionEdges = new MapMaker()
                .concurrencyLevel(configuration.getNettyServerExecutionConcurrency()).makeMap();
        partitionEdges = transientEdges.putIfAbsent(partitionId, newPartitionEdges);
        if (partitionEdges == null) {
            partitionEdges = newPartitionEdges;
        }
    }
    ByteArrayVertexIdEdges<I, E>.VertexIdEdgeIterator vertexIdEdgeIterator = edges.getVertexIdEdgeIterator();
    while (vertexIdEdgeIterator.hasNext()) {
        vertexIdEdgeIterator.next();
        I vertexId = vertexIdEdgeIterator.getCurrentVertexId();
        Edge<I, E> edge = reuseEdgeObjects ? vertexIdEdgeIterator.getCurrentEdge()
                : vertexIdEdgeIterator.releaseCurrentEdge();
        OutEdges<I, E> outEdges = partitionEdges.get(vertexId);
        if (outEdges == null) {
            OutEdges<I, E> newOutEdges = configuration.createAndInitializeInputOutEdges();
            outEdges = partitionEdges.putIfAbsent(vertexId, newOutEdges);
            if (outEdges == null) {
                outEdges = newOutEdges;
                // Since we had to use the vertex id as a new key in the map,
                // we need to release the object.
                vertexIdEdgeIterator.releaseCurrentVertexId();
            }
        }
        synchronized (outEdges) {
            outEdges.add(edge);
        }
    }
}

From source file:net.minecrell.serverlistplus.core.player.JSONIdentificationStorage.java

@Override
public synchronized void enable() throws ServerListPlusException {
    if (isEnabled())
        return;/*from w  w  w  .  j a va2s  .c  om*/

    getLogger().log(INFO, "Reloading saved player identities...");
    Path storagePath = getStoragePath();
    getLogger().log(DEBUG, "Storage location: " + storagePath);

    this.storage = new MapMaker().makeMap();

    try {
        if (Files.exists(storagePath)) {
            Map<InetAddress, PlayerIdentity> identities;

            try (Reader reader = IOHelper.newBufferedReader(storagePath)) {
                identities = JSON.fromJson(reader, STORAGE_TYPE);
            }

            if (identities != null)
                storage.putAll(identities);
        }

        getLogger().log(DEBUG, "Player identities successfully reloaded from file.");
    } catch (JsonSyntaxException e) {
        throw getLogger().process(e, "Unable to parse player storage, have you changed it?");
    } catch (IOException | JsonIOException e) {
        throw getLogger().process(e,
                "Unable to read player storage, make sure it is accessible by the " + "server");
    } catch (Exception e) {
        throw getLogger().process(e, "Failed to load player storage.");
    }

    changed.set(false);

    TimeUnitValue delay = ((Conf) core.getConf(PluginConf.class).PlayerTracking.Storage).SaveDelay;
    this.saveTask = core.getPlugin().scheduleAsync(new SaveTask(), delay.getValue(), delay.getUnit());
}

From source file:com.voxelplugineering.voxelsniper.service.eventbus.AsyncEventBus.java

@Override
public void _init() {
    if (this.built) {
        return;/*from w w  w .  j  av  a  2 s.  co m*/
    }
    this.registry = new MapMaker().concurrencyLevel(4).makeMap();
    if (!this.explicitExecutor) {
        final String prefix = this.config.get("eventBusThreadPrefix", String.class)
                .or("AsyncEventBus-executor-");
        this.executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool(new ThreadFactory() {

            private final ThreadGroup group;
            private int count;

            {
                this.group = Thread.currentThread().getThreadGroup();
            }

            @Override
            public Thread newThread(Runnable r) {
                Thread thr = new Thread(this.group, r, prefix + this.count++);
                return thr;
            }
        }));
    }
    this.built = true;
}

From source file:com.boardhood.mobile.cache.AbstractCache.java

/**
 * Creates a new cache instance.//from w w  w .  j a  v  a 2s  . co m
 * 
 * @param name
 *            a human readable identifier for this cache. Note that this value will be used to
 *            derive a directory name if the disk cache is enabled, so don't get too creative
 *            here (camel case names work great)
 * @param initialCapacity
 *            the initial element size of the cache
 * @param maxConcurrentThreads
 *            how many threads you think may at once access the cache; this need not be an exact
 *            number, but it helps in fragmenting the cache properly
 */
public AbstractCache(String name, int initialCapacity, int maxConcurrentThreads) {
    this.name = name;
    MapMaker mapMaker = new MapMaker();
    mapMaker.initialCapacity(initialCapacity);
    mapMaker.concurrencyLevel(maxConcurrentThreads);
    mapMaker.softValues();
    this.cache = mapMaker.makeMap();
}

From source file:com.yelp.android.webimageview.ImageCache.java

public ImageCache(Context context, int initialCapacity, int concurrencyLevel) {
    mContext = context;// w  ww  .j  a v  a  2 s.c  o  m
    this.mCache = new MapMaker().initialCapacity(initialCapacity).concurrencyLevel(concurrencyLevel)
            .softValues().makeMap();
    this.mPermanentCacheDir = new File(
            context.getApplicationContext().getCacheDir().getAbsolutePath() + "/permanent_images");
    this.mInternalCacheDir = new File(context.getApplicationContext().getCacheDir() + "/droidfu/imagecache");
    updateExternalStorageState(context);
    registerForExternalStorageUpdates(context);
}