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:com.voxelplugineering.voxelsniper.event.bus.AsyncEventBus.java

/**
 * Creates a new {@link AsyncEventBus}. This defaults to using
 * {@link Executors#newCachedThreadPool()} for event handler delegation.
 *///from  ww w.  j  a v a 2  s .c o m
public AsyncEventBus() {
    final String prefix = Gunsmith.getConfiguration().get("eventBusThreadPrefix", String.class)
            .or("AsyncEventBus-executor-");
    this.executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool(new ThreadFactory() {

        private final ThreadGroup group;
        private int count = 0;

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

        @Override
        public Thread newThread(Runnable r) {
            Thread thr = new Thread(this.group, r, prefix + this.count++);
            return thr;
        }
    }));
    this.registry = new MapMaker().concurrencyLevel(4).makeMap();
}

From source file:com.prealpha.xylophone.server.PublishingDispatcherImpl.java

/**
 * Constructs a new {@code DispatcherImpl}, using the specified
 * {@link Injector} to obtain action handlers and the specified provider to
 * obtain {@code AsyncContext} instances.
 * /*from w w  w.  j  av  a2 s .c  om*/
 * @param injector
 *            the injector to use to obtain action handlers
 * @param contextProvider
 *            the provider to use to obtain active {@code AsyncContext}
 *            instances
 */
@Inject
private PublishingDispatcherImpl(Injector injector, Provider<AsyncContext> contextProvider) {
    this.injector = injector;
    this.contextProvider = contextProvider;
    subscriptions = new MapMaker().makeMap();
    nextSubscriptionId = new AtomicLong();
}

From source file:com.codingfingers.fastimagelist.cache.AbstractCache.java

protected MapMaker createMapMaker(int initialCapacity, long expirationInMinutes, int maxConcurrentThreads) {
    MapMaker mapMaker = new MapMaker();
    mapMaker.initialCapacity(initialCapacity);
    mapMaker.expiration(expirationInMinutes * 60, TimeUnit.SECONDS);
    mapMaker.concurrencyLevel(maxConcurrentThreads);
    //        mapMaker.softValues();
    return mapMaker;
}

From source file:com.quinsoft.zeidon.domains.DoubleDomain.java

private synchronized ConcurrentMap<String, DomainContext> getAdhocContextMap() {
    if (adhocContexts == null)
        adhocContexts = new MapMaker().concurrencyLevel(2).makeMap();

    return adhocContexts;
}

From source file:de.cosmocode.palava.ipc.session.store.Session.java

private void hydrate() {
    Preconditions.checkState(!isHydrated(), "session %s is already hydrated", this);
    LOG.trace("Hydrating {}", this);

    try {/*from  ww w. ja  v a  2  s  . c  om*/
        final ObjectInputStream stream = new ObjectInputStream(store.read(sessionId));

        try {
            @SuppressWarnings("unchecked")
            final ConcurrentMap<Object, Object> map = (ConcurrentMap<Object, Object>) stream.readObject();
            this.data = map;
        } finally {
            stream.close();
        }

        store.delete(sessionId);
    } catch (IOException e) {
        LOG.error("IO exception on loading session data for " + this, e);
        this.data = null;
    } catch (ClassNotFoundException e) {
        LOG.error("Incompatible session data found for " + this, e);
        this.data = null;
    } catch (IllegalStateException e) {
        LOG.error("Session data not found for " + this, e);
        this.data = null;
    } finally {
        if (this.data == null) {
            LOG.warn("Hydrating failed, continuing with a vanilla session.");
            this.data = new MapMaker().makeMap();
        }
    }
}

From source file:net.tomp2p.storage.TrackerStorage.java

public TrackerStorage(IdentityManagement identityManagement, int trackerTimoutSeconds, Replication replication,
        Maintenance maintenance) {/*from  w ww  .  j  av a 2s.com*/
    this.trackerTimoutSeconds = trackerTimoutSeconds;
    this.identityManagement = identityManagement;
    this.replication = replication;
    this.maintenance = maintenance;
    trackerDataActive = new MapMaker().makeMap();
    trackerDataMesh = new MapMaker().expireAfterAccess(trackerTimoutSeconds, TimeUnit.SECONDS).makeMap();
    trackerDataSecondary = new MapMaker().expireAfterAccess(trackerTimoutSeconds, TimeUnit.SECONDS).makeMap();
    //
    reverseTrackerDataMesh = new MapMaker().expireAfterAccess(trackerTimoutSeconds, TimeUnit.SECONDS).makeMap();
    reverseTrackerDataSecondary = new MapMaker().expireAfterAccess(trackerTimoutSeconds, TimeUnit.SECONDS)
            .makeMap();
    // if everything is perfect, a factor of 2 is enough, to be on the safe
    // side factor 5 is used.
    peerOffline = new MapMaker().expireAfterAccess(trackerTimoutSeconds * 5, TimeUnit.SECONDS).makeMap();

}

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

/**
 * Created for test purpose.// ww  w  .j  av a2  s  . co m
 * @param config
 * @param sessionTransaction
 * @param ticker 
 */
protected DefaultCursorManager(TorodConfig config, SessionTransaction sessionTransaction, Ticker ticker) {
    this.actualTimeout = config.getDefaultCursorTimeout();
    this.sessionTransaction = sessionTransaction;
    this.removalListener = new MyRemovalListener();
    this.ticker = ticker;

    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:com.zimbra.cs.lmtpserver.ZimbraLmtpBackend.java

private static Map<Integer, ReentrantLock> createMailboxDeliveryLocks() {
    Function<Integer, ReentrantLock> lockCreator = new Function<Integer, ReentrantLock>() {
        @Override// ww  w .j  a  va  2s  .  c  o m
        public ReentrantLock apply(Integer from) {
            return new ReentrantLock();
        }
    };
    return new MapMaker().makeComputingMap(lockCreator);
}

From source file:com.b2international.snowowl.datastore.server.CDOServerChangeManager.java

public CDOServerChangeManager(final String repositoryUuid, final String repositoryName) {
    super(false);
    this.repositoryName = repositoryName;
    this.factories = CDOChangeProcessorFactoryManager.INSTANCE
            .getFactories(checkNotNull(repositoryUuid, "Repository UUID argument cannot be null."));
    this.activeChangeManagers = new MapMaker().makeMap();
}

From source file:fr.xebia.demo.amazon.aws.AmazonAwsShutdowner.java

public void test() {
    String ownerId = "self";

    boolean dryRun = true;

    // RETRIEVE TAGS
    Map<String, Map<String, String>> tagsByResourceId = new MapMaker()
            .makeComputingMap(new Function<String, Map<String, String>>() {
                @Override//from  w ww .j a  va  2 s.  com
                public Map<String, String> apply(String input) {
                    return Maps.newHashMap();
                }
            });

    for (TagDescription tagDescription : ec2.describeTags().getTags()) {
        tagsByResourceId.get(tagDescription.getResourceId()).put(tagDescription.getKey(),
                tagDescription.getValue());
    }

    // RDS INSTANCEs
    for (DBInstance dbInstance : rds.describeDBInstances().getDBInstances()) {
        Map<String, String> instanceTags = tagsByResourceId.get(dbInstance.getDBInstanceIdentifier());
        logger.debug("Tags for " + dbInstance + ": " + instanceTags);

    }

    // EC2 INSTANCES
    List<Instance> instancesAlreadyNotStarted = Lists.newArrayList();
    List<Instance> instancesToStop = Lists.newArrayList();
    List<Instance> instancesToTerminate = Lists.newArrayList();
    List<Instance> instancesToKeepUnchanged = Lists.newArrayList();
    for (Reservation reservation : ec2.describeInstances().getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            Map<String, String> instanceTags = tagsByResourceId.get(instance.getInstanceId());
            logger.debug("Tags for {}: {}", instance, instanceTags);
            if ("terminated".equals(instance.getState().getName())) {
                instancesToKeepUnchanged.add(instance);
            } else if (instanceTags.containsKey(TAG_DO_NOT_STOP)) {
                instancesToKeepUnchanged.add(instance);
            } else if (instanceTags.containsKey(TAG_DO_NOT_TERMINATE)) {
                if ("started".equals(instance.getState().getName())) {
                    instancesToStop.add(instance);
                } else {
                    instancesAlreadyNotStarted.add(instance);
                }
            } else {
                instancesToTerminate.add(instance);
            }
        }
    }
    System.out.println("EC2 INSTANCES");
    if (dryRun) {
        System.out.println("DRY RUN Terminate:" + instancesToTerminate);
        System.out.println("DRY RUN Stop:" + instancesToStop);
        System.out.println("DRY RUN No need to stop:" + instancesAlreadyNotStarted);
        System.out.println("DRY RUN Keep unchanged:" + instancesToKeepUnchanged);
    } else {
        System.out.println("Terminate:" + instancesToTerminate);
        if (!instancesToTerminate.isEmpty()) {
            ec2.terminateInstances(new TerminateInstancesRequest(
                    Lists.transform(instancesToTerminate, TO_INSTANCE_ID_FUNCTION)));
        }
        System.out.println("Stop:" + instancesToStop);
        if (!instancesToStop.isEmpty()) {
            ec2.stopInstances(
                    new StopInstancesRequest(Lists.transform(instancesToStop, TO_INSTANCE_ID_FUNCTION)));
        }
        System.out.println("No need to stop:" + instancesAlreadyNotStarted);
        System.out.println("Keep unchanged:" + instancesToKeepUnchanged);
    }

    // AMIs
    System.out.println("AMIs");
    List<Image> imagesToDeRegister = Lists.newArrayList();
    List<Image> imagesToKeep = Lists.newArrayList();
    for (Image image : ec2.describeImages(new DescribeImagesRequest().withOwners(ownerId)).getImages()) {
        Map<String, String> imageTags = tagsByResourceId.get(image.getImageId());
        logger.debug("Tags for {}: {}", image, imageTags);
        if (imageTags.containsKey(TAG_DO_NOT_DEREGISTER)) {
            imagesToKeep.add(image);
        } else {
            imagesToDeRegister.add(image);
        }
    }
    if (dryRun) {
        System.out.println("DRY RUN Deregister:" + imagesToDeRegister);
        System.out.println("DRY RUN Keep:" + imagesToKeep);

    } else {
        System.out.println("Deregister:" + imagesToDeRegister);
        for (Image image : imagesToDeRegister) {
            ec2.deregisterImage(new DeregisterImageRequest(image.getImageId()));
        }
        System.out.println("Keep:" + imagesToKeep);
    }

    List<String> imageIdsToKeep = Lists.transform(imagesToKeep, TO_IMAGE_ID_FUNCTION);

    // SNAPSHOTS
    System.out.println("SNAPSHOTs");
    for (Snapshot snapshot : ec2.describeSnapshots(new DescribeSnapshotsRequest().withOwnerIds(ownerId))
            .getSnapshots()) {

        if (snapshot.getDescription().contains("Created by CreateImage")) {
            boolean associatedWithAnImageToKeep = false;
            for (String imageIdToKeep : imageIdsToKeep) {
                if (snapshot.getDescription().contains(imageIdToKeep)) {
                    associatedWithAnImageToKeep = true;
                    break;
                }
            }
            if (associatedWithAnImageToKeep) {
                System.out.println("Keep: " + snapshot);
            } else {
                if (dryRun) {
                    System.out.println("DRY RUN delete: " + snapshot);
                } else {
                    System.out.println("Delete: " + snapshot);
                    ec2.deleteSnapshot(new DeleteSnapshotRequest(snapshot.getSnapshotId()));
                }
            }
        }
    }
    // ELASTIC LOAD BALANCERs
    // no tags on elb
}