Example usage for com.google.common.collect Maps newHashMapWithExpectedSize

List of usage examples for com.google.common.collect Maps newHashMapWithExpectedSize

Introduction

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

Prototype

public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) 

Source Link

Document

Creates a HashMap instance, with a high enough "initial capacity" that it should hold expectedSize elements without growth.

Usage

From source file:com.aipo.container.gadgets.uri.AipoProxyUriManager.java

public List<Uri> make(List<ProxyUri> resources, Integer forcedRefresh) {
    if (resources.isEmpty()) {
        return Collections.emptyList();
    }//w ww.  jav a2 s.c o m

    List<Uri> resourceUris = Lists.newArrayListWithCapacity(resources.size());

    for (ProxyUri puc : resources) {
        resourceUris.add(puc.getResource());
    }

    Map<Uri, String> versions;
    if (versioner == null) {
        versions = Collections.emptyMap();
    } else {
        versions = Maps.newHashMapWithExpectedSize(resources.size());
        List<String> versionList = versioner.version(resourceUris, resources.get(0).getContainer());
        if (versionList != null && versionList.size() == resources.size()) {
            // This should always be the case.
            // Should we error if not, or just WARNING?
            Iterator<String> versionIt = versionList.iterator();
            for (ProxyUri puc : resources) {
                versions.put(puc.getResource(), versionIt.next());
            }
        }
    }

    List<Uri> result = Lists.newArrayListWithCapacity(resources.size());
    for (ProxyUri puc : resources) {
        result.add(makeProxiedUri(puc, forcedRefresh, versions.get(puc.getResource())));
    }

    return result;
}

From source file:com.opengamma.engine.marketdata.CombinedMarketDataSnapshot.java

@Override
public Map<ValueSpecification, Object> query(final Set<ValueSpecification> values) {
    final Map<ValueSpecification, Object> result = Maps.newHashMapWithExpectedSize(values.size());
    final Map<MarketDataProvider, Map<ValueSpecification, ValueSpecification>> groupByProvider = _combinedMarketDataProvider
            .getProvidersAsMap(values);// w  w  w  .j a v  a  2  s .co  m
    for (final Entry<MarketDataProvider, Map<ValueSpecification, ValueSpecification>> entry : groupByProvider
            .entrySet()) {
        for (Map.Entry<ValueSpecification, Object> innerResult : _snapshotByProvider.get(entry.getKey())
                .query(entry.getValue().keySet()).entrySet()) {
            result.put(entry.getValue().get(innerResult.getKey()), innerResult.getValue());
        }
    }
    return result;
}

From source file:org.gradoop.flink.algorithms.fsm.transactional.tle.functions.SubgraphDecoder.java

/**
 * Turns the subgraph into a Gradoop graph transaction.
 *
 * @param subgraph subgraph/*from   w w  w . j  a  v a 2s .c om*/
 * @param canonicalLabel canonical label
 * @return graph transaction
 */
protected GraphTransaction createTransaction(Subgraph subgraph, String canonicalLabel) {

    // GRAPH HEAD

    Properties properties = new Properties();

    properties.set(TFSMConstants.SUPPORT_KEY, subgraph.getCount());
    properties.set(TFSMConstants.CANONICAL_LABEL_KEY, subgraph.getCanonicalLabel());

    GraphHead epgmGraphHead = graphHeadFactory.createGraphHead(canonicalLabel, properties);

    GradoopIdSet graphIds = GradoopIdSet.fromExisting(epgmGraphHead.getId());

    // VERTICES

    Map<Integer, String> vertices = subgraph.getEmbedding().getVertices();
    Set<Vertex> epgmVertices = Sets.newHashSetWithExpectedSize(vertices.size());
    Map<Integer, GradoopId> vertexIdMap = Maps.newHashMapWithExpectedSize(vertices.size());

    for (Map.Entry<Integer, String> vertex : vertices.entrySet()) {
        Vertex epgmVertex = vertexFactory.createVertex(vertex.getValue(), graphIds);

        vertexIdMap.put(vertex.getKey(), epgmVertex.getId());
        epgmVertices.add(epgmVertex);
    }

    // EDGES

    Collection<FSMEdge> edges = subgraph.getEmbedding().getEdges().values();
    Set<Edge> epgmEdges = Sets.newHashSetWithExpectedSize(edges.size());

    for (FSMEdge edge : edges) {
        epgmEdges.add(edgeFactory.createEdge(edge.getLabel(), vertexIdMap.get(edge.getSourceId()),
                vertexIdMap.get(edge.getTargetId()), graphIds));
    }

    return new GraphTransaction(epgmGraphHead, epgmVertices, epgmEdges);
}

From source file:org.agatom.springatom.data.oid.impl.SOidServiceImpl.java

@PostConstruct
@SuppressWarnings("ConstantConditions")
private void readOidCreators() {
    Assert.notEmpty(oidCreators);/*from  ww  w .j a  v  a  2 s  . c o m*/
    final Map<OidCreatorKey, SOidCreator<?>> localMap = Maps
            .newHashMapWithExpectedSize(this.oidCreators.size());
    for (final SOidCreator<?> oidCreator : oidCreators) {

        final Class<?> supportedType = resolveTypeArgument(oidCreator.getClass(), SOidCreator.class);
        final String prefix = findAnnotation(oidCreator.getClass(), OidProvider.class).prefix();

        localMap.put(new OidCreatorKey().setPrefix(prefix).setSupportedClass(supportedType), oidCreator);
    }
    this.oidCreatorsMap = Collections.unmodifiableMap(localMap);
}

From source file:org.summer.dsl.xbase.typesystem.override.ResolvedOperationInHierarchy.java

@Override
protected TypeParameterSubstitutor<?> getSubstitutor() {
    if (isRawTypeInheritance()) {
        return new RawTypeSubstitutor(getContextType().getOwner());
    }/*  w ww  .  j  a v a  2  s .c  om*/
    TypeParameterSubstitutor<?> result = super.getSubstitutor();
    List<JvmTypeParameter> typeParameters = getTypeParameters();
    if (!typeParameters.isEmpty()) {
        List<JvmTypeParameter> resolvedTypeParameters = getResolvedTypeParameters();
        int max = Math.min(typeParameters.size(), resolvedTypeParameters.size());
        ITypeReferenceOwner owner = getContextType().getOwner();
        Map<JvmTypeParameter, LightweightMergedBoundTypeArgument> additionalMapping = Maps
                .newHashMapWithExpectedSize(max);
        for (int i = 0; i < max; i++) {
            ParameterizedTypeReference localReference = new ParameterizedTypeReference(owner,
                    resolvedTypeParameters.get(i));
            additionalMapping.put(typeParameters.get(i),
                    new LightweightMergedBoundTypeArgument(localReference, VarianceInfo.INVARIANT));
        }
        result.enhanceMapping(additionalMapping);
    }
    return result;
}

From source file:com.threerings.util.MethodProfiler.java

/**
 * Gets all method results so far.//from   w  w w .  ja  v  a 2s .c  om
 */
public Map<String, Result> getResults() {
    Map<String, RunningStats> cmap = _profiles.asMap();
    Map<String, Result> results = Maps.newHashMapWithExpectedSize(cmap.size());
    for (Map.Entry<String, RunningStats> entry : cmap.entrySet()) {
        synchronized (entry.getValue()) {
            results.put(entry.getKey(), toResult(entry.getValue()));
        }
    }
    return results;
}

From source file:org.gradle.internal.component.external.model.maven.RealisedMavenModuleResolveMetadata.java

/**
 * Factory method to transform a {@link DefaultMavenModuleResolveMetadata}, which is lazy, in a realised version.
 *
 * @param metadata the lazy metadata to transform
 * @return the realised version of the metadata
 *///  w  w  w.j  a v a  2  s . c  o m
public static RealisedMavenModuleResolveMetadata transform(DefaultMavenModuleResolveMetadata metadata) {
    VariantMetadataRules variantMetadataRules = metadata.getVariantMetadataRules();
    ImmutableList<? extends ComponentVariant> variants = LazyToRealisedModuleComponentResolveMetadataHelper
            .realiseVariants(metadata, variantMetadataRules, metadata.getVariants());

    boolean computeDerivedVariants = metadata.getVariants().size() == 0;
    List<ConfigurationMetadata> derivedVariants = Lists.newArrayListWithCapacity(2);
    Map<String, ConfigurationMetadata> configurations = Maps
            .newHashMapWithExpectedSize(metadata.getConfigurationNames().size());
    for (String configurationName : metadata.getConfigurationNames()) {
        ImmutableMap<String, Configuration> configurationDefinitions = metadata.getConfigurationDefinitions();
        Configuration configuration = configurationDefinitions.get(configurationName);

        NameOnlyVariantResolveMetadata variant = new NameOnlyVariantResolveMetadata(configurationName);
        ImmutableAttributes variantAttributes = variantMetadataRules.applyVariantAttributeRules(variant,
                metadata.getAttributes());
        CapabilitiesMetadata capabilitiesMetadata = variantMetadataRules.applyCapabilitiesRules(variant,
                ImmutableCapabilities.EMPTY);

        RealisedConfigurationMetadata realisedConfiguration = createConfiguration(variantMetadataRules,
                metadata.getId(), configurationName, configuration.isTransitive(), configuration.isVisible(),
                LazyToRealisedModuleComponentResolveMetadataHelper.constructHierarchy(configuration,
                        configurationDefinitions),
                metadata.getDependencies(), metadata.isImprovedPomSupportEnabled(), variantAttributes,
                ImmutableCapabilities.of(capabilitiesMetadata.getCapabilities()));
        configurations.put(configurationName, realisedConfiguration);

        if (computeDerivedVariants) {
            if (configurationName.equals("compile")) {
                derivedVariants.add(withUsageAttribute(realisedConfiguration, Usage.JAVA_API,
                        metadata.getAttributesFactory(), variantAttributes, metadata.getObjectInstantiator()));
            } else if (configurationName.equals("runtime")) {
                derivedVariants.add(withUsageAttribute(realisedConfiguration, Usage.JAVA_RUNTIME,
                        metadata.getAttributesFactory(), variantAttributes, metadata.getObjectInstantiator()));
            }
        }
    }
    return new RealisedMavenModuleResolveMetadata(metadata, variants, derivedVariants, configurations);
}

From source file:org.novelang.build.unicode.UnicodeNamesGenerator.java

/**
 *  Generates the offset table and the names.
 *
 * @param outputStream not flushed./* w  w  w .  j a  va2  s  .co m*/
 * @param characterNames a Map with characters having contiguous codes that start by 0.
 */
public static void generate(final OutputStream outputStream, final Map<Character, String> characterNames,
        final int totalCharacterCount) throws IOException {
    Preconditions.checkArgument(totalCharacterCount <= UNSIGNED_MAX_16BIT);
    final Map<Integer, Integer> offsetsFromFirstName = Maps.newHashMapWithExpectedSize(totalCharacterCount);
    final Map<Character, byte[]> characterNamesAsBytes = calculateCharacterNamesAsBytes(characterNames);

    // Find the offset of the name of each character.
    int writePositionFromFirstName = 0;
    int characterCount = 0;

    for (int characterIndex = 0; characterIndex < totalCharacterCount; characterIndex++) {
        final Character character = (char) characterIndex;
        if (characterNames.containsKey(character)) {
            offsetsFromFirstName.put(characterIndex, writePositionFromFirstName);
            writePositionFromFirstName += characterNamesAsBytes.get(character).length + // Real length.
                    1 // Terminal zero.
            ;
            characterCount++;
        } else {
            offsetsFromFirstName.put(characterIndex, null);
        }
    }
    LOGGER.debug("Found " + characterCount + " characters.");

    // Write character count.
    outputStream.write(asBytes(totalCharacterCount));

    // Write offsets.
    final int offsetTableSize = totalCharacterCount * 4;
    for (int characterIndex = 0; characterIndex < totalCharacterCount; characterIndex++) {
        final byte[] bytes;
        final Integer value = offsetsFromFirstName.get(characterIndex);
        if (value == null) {
            bytes = ZERO_OFFSET;
        } else {
            bytes = asBytes(4 + offsetTableSize + value);
        }
        outputStream.write(bytes);
    }

    // Write names.
    for (int characterIndex = 0; characterIndex < totalCharacterCount; characterIndex++) {
        final byte[] nameBytes = characterNamesAsBytes.get((char) characterIndex);
        if (nameBytes != null) {
            outputStream.write(nameBytes);
            outputStream.write(TERMINAL_ZERO);
        }
    }
    outputStream.flush();
    LOGGER.debug("Generation complete.");

}

From source file:voldemort.server.scheduler.slop.BlockingSlopPusherJob.java

/**
 * Loop over entries in the slop table and attempt to push them to the
 * deserving server/*from  w  ww. j a v  a2 s  .  c  o  m*/
 */
public void run() {

    // don't try to run slop pusher job when rebalancing
    if (metadataStore.getServerStateUnlocked().equals(MetadataStore.VoldemortState.REBALANCING_MASTER_SERVER)) {
        logger.error("Cannot run slop pusher job since Voldemort server is rebalancing");
        return;
    }

    logger.info("Started blocking slop pusher job at " + new Date());

    Cluster cluster = metadataStore.getCluster();
    Set<String> storeNames = StoreDefinitionUtils.getStoreNamesSet(metadataStore.getStoreDefList());

    ClosableIterator<Pair<ByteArray, Versioned<Slop>>> iterator = null;

    Map<Integer, Long> attemptedByNode = Maps.newHashMapWithExpectedSize(cluster.getNumberOfNodes());
    Map<Integer, Long> succeededByNode = Maps.newHashMapWithExpectedSize(cluster.getNumberOfNodes());
    long slopsPushed = 0L;
    long attemptedPushes = 0L;
    for (Node node : cluster.getNodes()) {
        attemptedByNode.put(node.getId(), 0L);
        succeededByNode.put(node.getId(), 0L);
    }

    acquireRepairPermit();
    try {
        SlopStorageEngine slopStorageEngine = storeRepo.getSlopStore();
        StorageEngine<ByteArray, Slop, byte[]> slopStore = slopStorageEngine.asSlopStore();
        EventThrottler throttler = new EventThrottler(maxWriteBytesPerSec);

        iterator = slopStore.entries();

        while (iterator.hasNext()) {
            if (Thread.interrupted())
                throw new InterruptedException("Slop pusher job cancelled");

            try {
                Pair<ByteArray, Versioned<Slop>> keyAndVal;
                try {
                    keyAndVal = iterator.next();
                } catch (Exception e) {
                    logger.error("Exception in iterator, escaping the loop ", e);
                    break;
                }

                Versioned<Slop> versioned = keyAndVal.getSecond();
                Slop slop = versioned.getValue();
                int nodeId = slop.getNodeId();

                // check for dead slops
                if (isSlopDead(cluster, storeNames, versioned.getValue())) {
                    handleDeadSlop(slopStorageEngine, keyAndVal);
                    // No matter we deleted it or not, we need to move onto
                    // the next slop.
                    continue;
                }

                Node node = cluster.getNodeById(nodeId);

                attemptedPushes++;
                if (attemptedPushes % 10000 == 0) {
                    logger.info("Attempted pushing " + attemptedPushes + " slops");
                }
                Long attempted = attemptedByNode.get(nodeId);
                attemptedByNode.put(nodeId, attempted + 1L);

                if (failureDetector.isAvailable(node)) {
                    Store<ByteArray, byte[], byte[]> store = storeRepo.getNodeStore(slop.getStoreName(),
                            node.getId());
                    Long startNs = System.nanoTime();
                    int nBytes = 0;
                    try {
                        nBytes = slop.getKey().length();
                        if (slop.getOperation() == Operation.PUT) {
                            store.put(slop.getKey(),
                                    new Versioned<byte[]>(slop.getValue(), versioned.getVersion()),
                                    slop.getTransforms());
                            nBytes += slop.getValue().length
                                    + ((VectorClock) versioned.getVersion()).sizeInBytes() + 1;

                        } else if (slop.getOperation() == Operation.DELETE) {
                            nBytes += ((VectorClock) versioned.getVersion()).sizeInBytes() + 1;
                            store.delete(slop.getKey(), versioned.getVersion());
                        } else {
                            logger.error("Unknown slop operation: " + slop.getOperation());
                            continue;
                        }
                        failureDetector.recordSuccess(node, deltaMs(startNs));
                        slopStore.delete(slop.makeKey(), versioned.getVersion());

                        slopsPushed++;
                        // Increment succeeded
                        Long succeeded = succeededByNode.get(nodeId);
                        succeededByNode.put(nodeId, succeeded + 1L);

                        // Throttle the bytes...
                        throttler.maybeThrottle(nBytes);

                    } catch (ObsoleteVersionException e) {

                        // okay it is old, just delete it
                        slopStore.delete(slop.makeKey(), versioned.getVersion());
                        slopsPushed++;

                        // Increment succeeded
                        Long succeeded = succeededByNode.get(nodeId);
                        succeededByNode.put(nodeId, succeeded + 1L);

                        // Throttle the bytes...
                        throttler.maybeThrottle(nBytes);

                    } catch (UnreachableStoreException e) {
                        failureDetector.recordException(node, deltaMs(startNs), e);
                    }
                }
            } catch (Exception e) {
                logger.error(e, e);
            }
        }

        // Only if we reached here do we update stats
        logger.log(attemptedPushes > 0 ? Level.INFO : Level.DEBUG, "Attempted " + attemptedPushes
                + " hinted handoff pushes of which " + slopsPushed + " succeeded.");

        Map<Integer, Long> outstanding = Maps.newHashMapWithExpectedSize(cluster.getNumberOfNodes());
        for (int nodeId : succeededByNode.keySet()) {
            outstanding.put(nodeId, attemptedByNode.get(nodeId) - succeededByNode.get(nodeId));
        }

        slopStorageEngine.resetStats(outstanding);

    } catch (Exception e) {
        logger.error(e, e);
    } finally {
        try {
            if (iterator != null)
                iterator.close();
        } catch (Exception e) {
            logger.error("Failed to close iterator.", e);
        }
        this.repairPermits.release(this.getClass().getCanonicalName());
    }
}

From source file:com.android.tools.idea.rendering.ContextPullParser.java

@Override
@Nullable//ww w  .  j a  v  a 2s  . c  om
public Object getViewCookie() {
    String name = super.getName();
    if (name == null) {
        return null;
    }

    // Store tools attributes if this looks like a layout we'll need adapter view
    // bindings for in the ProjectCallback.
    if (LIST_VIEW.equals(name) || EXPANDABLE_LIST_VIEW.equals(name) || GRID_VIEW.equals(name)
            || SPINNER.equals(name)) {
        Map<String, String> map = null;
        int count = getAttributeCount();
        for (int i = 0; i < count; i++) {
            String namespace = getAttributeNamespace(i);
            if (namespace != null && namespace.equals(TOOLS_URI)) {
                String attribute = getAttributeName(i);
                if (attribute.equals(ATTR_IGNORE)) {
                    continue;
                }
                if (map == null) {
                    map = Maps.newHashMapWithExpectedSize(4);
                }
                map.put(attribute, getAttributeValue(i));
            }
        }

        return map;
    }

    return null;
}