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:io.warp10.standalone.StandaloneMemoryStore.java

public StandaloneMemoryStore(KeyStore keystore, long timespan, long highwatermark, long lowwatermark) {
    this.keystore = keystore;
    this.aesKey = this.keystore.getKey(KeyStore.AES_LEVELDB_DATA);
    //this.series = new ConcurrentHashMap<BigInteger,GTSEncoder>();
    this.series = new MapMaker().concurrencyLevel(64).makeMap();
    this.timespan = timespan;
    this.highwatermark = highwatermark;
    this.lowwatermark = lowwatermark;

    ///*from   w  w  w .  ja  va  2 s . com*/
    // Add a shutdown hook to dump the memory store on exit
    //

    if (null != WarpConfig.getProperties().getProperty(STANDALONE_MEMORY_STORE_DUMP)) {

        final StandaloneMemoryStore self = this;
        final String path = WarpConfig.getProperties().getProperty(STANDALONE_MEMORY_STORE_DUMP);
        Thread dumphook = new Thread() {
            @Override
            public void run() {
                try {
                    self.dump(path);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    throw new RuntimeException(ioe);
                }
            }
        };

        Runtime.getRuntime().addShutdownHook(dumphook);

        //
        // Make sure ShutdownHookManager is initialized, otherwise it will try to
        // register a shutdown hook during the shutdown hook we just registered...
        //

        ShutdownHookManager.get();
    }

    this.setDaemon(true);
    this.setName("[StandaloneMemoryStore Janitor]");
    this.setPriority(Thread.MIN_PRIORITY);
    this.start();
}

From source file:com.toro.torod.cursors.DefaultInnerCursorManager.java

/**
 * Created for test purpose.//from  ww w  . j  a  v a  2  s .co  m
 * @param config
 * @param sessionTransaction
 * @param ticker 
 */
protected DefaultInnerCursorManager(TorodConfig config, DbWrapper dbWrapper, Ticker ticker) {
    this.actualTimeout = config.getDefaultCursorTimeout();
    this.removalListener = new MyRemovalListener();
    this.ticker = ticker;
    this.dbWrapper = dbWrapper;

    withoutTimeout = new MapMaker().makeMap();
    withTimeout = createCache(actualTimeout);
    oldCaches = Collections.newSetFromMap(new MapMaker().<Cache<CursorId, CursorProperties>, Boolean>makeMap());

    readElementMap = new MapMaker().makeMap();

    cursorIdProvider = new AtomicLong(FIRST_CURSOR_ID);
}

From source file:me.schiz.jmeter.ring.udp.Ring.java

public Ring init() {
    hashedWheelTimer = new HashedWheelTimer();
    eventLoopRunnables = new EventLoopRunnable[THREADS];
    for (int i = 0; i < selectorsCount; ++i) {
        eventLoopRunnables[i] = new EventLoopRunnable(this);
        threads[i] = new Thread(eventLoopRunnables[i]);
        threads[i].setDaemon(true);/*from w  w w  .j av a2  s.co  m*/
        threads[i].setName("EventLoopThread#" + i);
    }

    weakSocketToTokenMap = new MapMaker().concurrencyLevel(Runtime.getRuntime().availableProcessors())
            .initialCapacity(capacity).softKeys().makeMap();

    for (int i = 0; i < capacity; 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.datagramChannel);
            try {
                eventLoopRunnables[i % selectorsCount].register(t.datagramChannel, SelectionKey.OP_READ);
            } catch (InterruptedException e) {
                log.error("InterruptedException when register SocketChannel", e);
                break;
            }
            ring.get(i).datagramChannel.connect(ring.get(i).targetAddress);
            weakSocketToTokenMap.putIfAbsent(t.datagramChannel, t);
        } catch (IOException e) {
            log.error("IOException ", e);
        }
    }

    for (int i = 0; i < selectorsCount; i++)
        threads[i].start();

    //schedEx.scheduleWithFixedDelay(new RingInfoRunnable(this), 0, 1000, TimeUnit.MILLISECONDS);

    return this;
}

From source file:com.ardor3d.bounding.CollisionTreeManager.java

/**
 * private constructor for the Singleton. Initializes the cache.
 *///from   www .jav  a  2  s . c  o  m
private CollisionTreeManager() {
    _cache = new MapMaker().weakKeys().makeMap();
    _protectedList = Collections.synchronizedList(new ArrayList<Mesh>(1));
    setCollisionTreeController(new UsageTreeController());
}

From source file:org.obm.servlet.filter.qos.handlers.TransactionalKeyRequestsInfoStore.java

@Inject
@VisibleForTesting
TransactionalKeyRequestsInfoStore() {
    references = Sets.newConcurrentHashSet();
    map = new MapMaker().weakValues().makeMap();
    count = new AtomicInteger();
}

From source file:io.druid.query.aggregation.atomcube.AtomCubeQueryResource.java

@POST
@Produces({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
@Consumes({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE, APPLICATION_SMILE })
public Response doPost(InputStream in, @QueryParam("pretty") String pretty,
        @Context final HttpServletRequest req // used only to get request content-type and remote address
) throws IOException {
    final long start = System.currentTimeMillis();
    final String reqContentType = req.getContentType();
    final boolean isSmile = SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(reqContentType)
            || APPLICATION_SMILE.equals(reqContentType);
    ObjectMapper objectMapper = isSmile ? smileMapper : jsonMapper;
    final String contentType = isSmile ? SmileMediaTypes.APPLICATION_JACKSON_SMILE : MediaType.APPLICATION_JSON;
    final ObjectWriter jsonWriter = pretty != null ? objectMapper.writerWithDefaultPrettyPrinter()
            : objectMapper.writer();/*from   w  w  w.  ja v  a2 s  .  co  m*/

    AtomCubeQuery _query = objectMapper.readValue(in, AtomCubeQuery.class);
    final AtomCubeQuery atomQ = (AtomCubeQuery) _query.withId(UUID.randomUUID().toString());
    final Map<String, Object> responseContext1 = new MapMaker().makeMap();
    Sequence res = atomQ.run(this.conglomerate.findFactory(atomQ).createRunner(null), responseContext1);
    final Sequence results;
    if (res == null) {
        results = Sequences.empty();
    } else {
        results = res;
    }

    final Yielder yielder = results.toYielder(null, new YieldingAccumulator() {
        @Override
        public Object accumulate(Object accumulated, Object in) {
            yield();
            return in;
        }
    });

    final Map<String, Object> responseContext = new MapMaker().makeMap();
    Response.ResponseBuilder builder = Response.ok(new StreamingOutput() {
        @Override
        public void write(OutputStream outputStream) throws IOException, WebApplicationException {
            CountingOutputStream os = new CountingOutputStream(outputStream);
            jsonWriter.writeValue(os, yielder);

            os.flush();
            os.close();

            final long queryTime = System.currentTimeMillis() - start;
            emitter.emit(DruidMetrics.makeQueryTimeMetric(null, jsonMapper, atomQ, req.getRemoteAddr())
                    .setDimension("success", "true").build("query/time", queryTime));
            emitter.emit(DruidMetrics.makeQueryTimeMetric(null, jsonMapper, atomQ, req.getRemoteAddr())
                    .build("query/bytes", os.getCount()));

            requestLogger.log(new RequestLogLine(new DateTime(), req.getRemoteAddr(), atomQ,
                    new QueryStats(ImmutableMap.<String, Object>of("query/time", queryTime, "query/bytes",
                            os.getCount(), "success", true))));
        }
    }, contentType).header("X-Druid-Query-Id", atomQ.getId());

    String responseCtxString = jsonMapper.writeValueAsString(responseContext);

    return builder.header("X-Druid-Response-Context", responseCtxString).build();
}

From source file:com.alibaba.otter.node.common.config.impl.ConfigClientServiceImpl.java

public void afterPropertiesSet() throws Exception {
    // ?nid??/*from www .java  2s .c  o m*/
    String nid = System.getProperty(NID_NAME);
    if (StringUtils.isEmpty(nid)) {
        throw new ConfigException("nid is not set!");
    }

    this.nid = Long.valueOf(nid);

    channelMapping = new MapMaker().makeComputingMap(new Function<Long, Long>() {

        public Long apply(Long pipelineId) {
            // ?pipline -> channel?
            FindChannelEvent event = new FindChannelEvent();
            event.setPipelineId(pipelineId);
            try {
                Object obj = nodeCommmunicationClient.callManager(event);
                if (obj != null && obj instanceof Channel) {
                    Channel channel = (Channel) obj;
                    updateMapping(channel, pipelineId);// 
                    channelCache.put(channel.getId(), channel);// channelCache
                    return channel.getId();
                }
            } catch (Exception e) {
                logger.error("call_manager_error", event.toString(), e);
            }

            throw new ConfigException("No Such Channel by pipelineId[" + pipelineId + "]");
        }
    });

    nodeCache = new RefreshMemoryMirror<Long, Node>(timeout, new ComputeFunction<Long, Node>() {

        public Node apply(Long key, Node oldValue) {
            FindNodeEvent event = new FindNodeEvent();
            event.setNid(key);
            try {
                Object obj = nodeCommmunicationClient.callManager(event);
                if (obj != null && obj instanceof Node) {
                    return (Node) obj;
                } else {
                    throw new ConfigException("No Such Node by id[" + key + "]");
                }
            } catch (Exception e) {
                logger.error("call_manager_error", event.toString(), e);
            }
            // 
            return oldValue;
        }
    });

    channelCache = new RefreshMemoryMirror<Long, Channel>(timeout, new ComputeFunction<Long, Channel>() {

        public Channel apply(Long key, Channel oldValue) {
            FindChannelEvent event = new FindChannelEvent();
            event.setChannelId(key);
            try {
                Object obj = nodeCommmunicationClient.callManager(event);
                if (obj != null && obj instanceof Channel) {
                    updateMapping((Channel) obj, null);// 
                    return (Channel) obj;
                } else {
                    throw new ConfigException("No Such Channel by pipelineId[" + key + "]");
                }
            } catch (Exception e) {
                logger.error("call_manager_error", event.toString(), e);
            }
            // 
            return oldValue;
        }
    });
}

From source file:com.google.devtools.build.lib.actions.cache.PersistentStringIndexer.java

private static <K, V> ConcurrentMap<K, V> newConcurrentMap(int expectedCapacity) {
    return new MapMaker().initialCapacity(expectedCapacity).makeMap();
}

From source file:com.analog.lyric.dimple.events.DimpleEventListener.java

/**
 * Constructs a new empty event listener.
 *//*from   w  w  w .j a  v  a  2 s  . c  o  m*/
public DimpleEventListener() {
    // We use ConcurrentMap so that readers don't have to lock it, but force updates to be single
    // threaded with a lock this so the concurrency level is set to one to minimize overhead.
    // Use weak keys to prevent listener from keeping event sources in memory if no one else is using them.
    _handlersForSource = new MapMaker().concurrencyLevel(1).weakKeys().makeMap();
}

From source file:org.apache.hadoop.hive.ql.exec.StatsNoJobTask.java

@Override
public int execute(DriverContext driverContext) {

    LOG.info("Executing stats (no job) task");

    String tableName = "";
    ExecutorService threadPool = null;
    Hive db = getHive();/*from   w  w  w . j  a v a  2s . c  om*/
    try {
        tableName = work.getTableSpecs().tableName;
        table = db.getTable(tableName);
        int numThreads = HiveConf.getIntVar(conf, ConfVars.HIVE_STATS_GATHER_NUM_THREADS);
        tableFullName = table.getDbName() + "." + table.getTableName();
        threadPool = Executors.newFixedThreadPool(numThreads,
                new ThreadFactoryBuilder().setDaemon(true).setNameFormat("StatsNoJobTask-Thread-%d").build());
        partUpdates = new MapMaker().concurrencyLevel(numThreads).makeMap();
        LOG.info("Initialized threadpool for stats computation with " + numThreads + " threads");
    } catch (HiveException e) {
        LOG.error("Cannot get table " + tableName, e);
        console.printError("Cannot get table " + tableName, e.toString());
    }

    return aggregateStats(threadPool, db);
}