java.util.WeakHashMap.computeIfAbsent()方法的使用及代码示例

x33g5p2x  于2022-02-02 转载在 其他  
字(9.1k)|赞(0)|评价(0)|浏览(112)

本文整理了Java中java.util.WeakHashMap.computeIfAbsent()方法的一些代码示例,展示了WeakHashMap.computeIfAbsent()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WeakHashMap.computeIfAbsent()方法的具体详情如下:
包路径:java.util.WeakHashMap
类名称:WeakHashMap
方法名:computeIfAbsent

WeakHashMap.computeIfAbsent介绍

暂无

代码示例

代码示例来源:origin: org.apache.ant/ant

private static synchronized void add(FailFast f) {
  MAP.computeIfAbsent(f.parent, k -> new HashSet<>()).add(f);
}

代码示例来源:origin: lettuce-io/lettuce-core

public static MethodTranslator of(Class<?> delegate, Class<?>... methodSources) {
  synchronized (TRANSLATOR_MAP) {
    return TRANSLATOR_MAP.computeIfAbsent(delegate, key -> new MethodTranslator(key, methodSources));
  }
}

代码示例来源:origin: jersey/jersey

@Override
public Object invoke(Object obj, Method method, Object... arguments) throws Throwable {
  Object instance = instances.computeIfAbsent(Thread.currentThread(), thread -> supplier.get());
  return super.invoke(instance, method, arguments);
}

代码示例来源:origin: org.apache.ant/ant

/**
 * Returns the buffer associated with the current thread.
 *
 * @return a BufferInfo for the current thread to write data to
 */
private BufferInfo getBufferInfo() {
  Thread current = Thread.currentThread();
  return buffers.computeIfAbsent(current, x -> {
    BufferInfo bufferInfo = new BufferInfo();
    bufferInfo.buffer = new ByteArrayOutputStream(INITIAL_SIZE);
    bufferInfo.crSeen = false;
    return bufferInfo;
  });
}

代码示例来源:origin: reactor/reactor-core

seenSchedulers.computeIfAbsent(scheduler, s -> {
  int schedulerDifferentiator = this.schedulerDifferentiator
      .computeIfAbsent(schedulerName, k -> new AtomicInteger(0))
executorDifferentiator.computeIfAbsent(scheduler, key -> new AtomicInteger(0))
           .getAndIncrement();

代码示例来源:origin: com.davidbracewell/mango

/**
* <p>Adds or gets the canonical version of the incoming object.</p>
*
* @param object The object to intern
* @return The interned value
* @throws NullPointerException if the object is null
*/
public synchronized E intern(@NonNull final E object) {
 return map.computeIfAbsent(object, o -> object);
}

代码示例来源:origin: org.snmp4j/snmp4j-agent

protected Map<OID, R> getNewRows(Request key) {
  if (newRows == null) {
    newRows = new WeakHashMap<Request, Map<OID, R>>(4);
  }
  Map<OID, R> rowMap = newRows.computeIfAbsent(key, k -> new HashMap<OID, R>(5));
  return rowMap;
}

代码示例来源:origin: aws/aws-encryption-sdk-java

private static synchronized long getFallbackObjectId(Object object) {
  return FALLBACK_COMPARATOR_MAP.computeIfAbsent(object, ignored -> FALLBACK_COUNTER.incrementAndGet());
}

代码示例来源:origin: dev.rico/rico-data

private synchronized <ID extends Serializable, B, E extends DataWithId<ID>> void addMapping(final B bean, final Class<E> entityClass, final ID id) {
  beanToIdMapper.computeIfAbsent(bean, b -> new HashMap<>())
      .put(entityClass, id);
}

代码示例来源:origin: eclipse/golo-lang

public static MethodHandle vtableLookup(InlineCache inlineCache, Object[] args) {
 Class<?> receiverClass = args[0].getClass();
 return inlineCache.vtable.computeIfAbsent(receiverClass, k -> lookupTarget(receiverClass, inlineCache, args));
}

代码示例来源:origin: io.lettuce/lettuce-core

public static MethodTranslator of(Class<?> delegate, Class<?>... methodSources) {
  synchronized (TRANSLATOR_MAP) {
    return TRANSLATOR_MAP.computeIfAbsent(delegate, key -> new MethodTranslator(key, methodSources));
  }
}

代码示例来源:origin: com.holon-platform.core/holon-core

/**
 * Get a priority-ordered list of the suitable {@link ExpressionResolver} for given expression and resolution type.
 * @param expressionType Expression type
 * @param resolvedType Resolution type
 * @return Expression resolvers list, empty if none
 */
@SuppressWarnings("unchecked")
private List<ExpressionResolver> getResolversForExpressionType(Class<?> expressionType, Class<?> resolvedType) {
  // check cache
  if (cache != null && cache.containsKey(expressionType) && cache.get(expressionType).containsKey(resolvedType)) {
    return cache.get(expressionType).get(resolvedType);
  }
  List<ExpressionResolver> expressionResolvers = resolvers.stream().filter(
      r -> r.getExpressionType().isAssignableFrom(expressionType) && r.getResolvedType() == resolvedType)
      .sorted(PRIORITY_COMPARATOR).collect(Collectors.toList());
  // cache resolvers
  if (cache != null) {
    cache.computeIfAbsent(expressionType, k -> new WeakHashMap<>()).put(resolvedType, expressionResolvers);
  }
  return expressionResolvers;
}

代码示例来源:origin: com.holon-platform.jpa/holon-datastore-jpa-querydsl

@SuppressWarnings("unchecked")
public static <T> EntityPath<T> resolvePath(ClassLoader classLoader, Class<? extends T> domainClass) {
  final ClassLoader cl = (classLoader != null) ? classLoader : ClassUtils.getDefaultClassLoader();
  // check cache
  Map<Class, EntityPath> mappings = ENTITY_PATHS.getOrDefault(cl, Collections.emptyMap());
  if (mappings.containsKey(domainClass)) {
    return mappings.get(domainClass);
  }
  String pathClassName = getQueryClassName(domainClass);
  try {
    Class<?> pathClass = Class.forName(pathClassName, true, domainClass.getClassLoader());
    Field field = getStaticFieldOfType(pathClass);
    if (field == null) {
      throw new IllegalStateException("Static field of type " + pathClass.getName() + " not found");
    } else {
      EntityPath entityPath = (EntityPath) field.get(null);
      if (entityPath != null) {
        // cache value
        ENTITY_PATHS.computeIfAbsent(cl, c -> new HashMap<>()).put(domainClass, entityPath);
      }
      return entityPath;
    }
  } catch (ClassNotFoundException e) {
    throw new IllegalArgumentException(
        "Query class " + pathClassName + " not found for domain class " + domainClass.getName(), e);
  } catch (IllegalAccessException e) {
    throw new IllegalArgumentException("Failed to get static field value for field", e);
  }
}

代码示例来源:origin: io.projectreactor/reactor-core

seenSchedulers.computeIfAbsent(scheduler, s -> {
  int schedulerDifferentiator = this.schedulerDifferentiator
      .computeIfAbsent(schedulerName, k -> new AtomicInteger(0))
executorDifferentiator.computeIfAbsent(scheduler, key -> new AtomicInteger(0))
           .getAndIncrement();

代码示例来源:origin: org.snmp4j/snmp4j-agent

protected synchronized ChangeSet addPendingChanges(SubRequest subRequest,
                          MOTableRow row,
                          boolean newRow) {
  if (pendingChanges == null) {
    pendingChanges = new WeakHashMap<>(4);
  }
  Map<OID, ChangeSet> rowMap =
      pendingChanges.computeIfAbsent(subRequest.getRequest(), k -> new HashMap<>(5));
  Variable[] values = new Variable[getColumnCount()];
  int lastChangedColumn =
      getChangesFromRequest(row.getIndex(), row, subRequest,
          values, newRow, newRow);
  ChangeSet changeSet = new ChangeSet(row.getIndex(), values);
  changeSet.lastChangedColumn = lastChangedColumn;
  rowMap.put(row.getIndex(), changeSet);
  return changeSet;
}

代码示例来源:origin: cwensel/cascading

/**
 * Method operate ...
 *
 * @param flowProcess  of FlowProcess
 * @param functionCall of FunctionCall<Context>
 */
@Override
public void operate( FlowProcess flowProcess, FunctionCall<Context> functionCall )
 {
 Context context = functionCall.getContext();
 Tuple result = context.tuple;
 String string = getValue( functionCall );
 if( string == null )
  string = "";
 String encoded =
  context.cache.computeIfAbsent( string, value ->
  {
  value = preDigest.apply( value );
  byte[] bytes = value.getBytes( getCharset() );
  byte[] digest = context.digest.digest( bytes ); // guaranteed single threading
  StringBuilder buffer = new StringBuilder();
  performEncoding( buffer, digest );
  buffer = postEncoding.apply( buffer );
  if( buffer.length() > maxLength )
   return buffer.substring( 0, maxLength );
  return buffer.toString();
  } );
 result.set( 0, encoded );
 functionCall.getOutputCollector().add( result );
 }

代码示例来源:origin: anba/es6draft

private ScriptObject createModuleObject(NodeModuleRecord module, Realm realm) {
  Constructor moduleConstructor = moduleConstructors.computeIfAbsent(realm, r -> {
    try {
      ModuleRecord mod = ScriptLoading.evalNativeModule(r, "module.jsm");
      return (Constructor) ScriptLoading.getModuleExport(mod, "default");
    } catch (MalformedNameException | ResolutionException e) {
      throw e.toScriptException(r.defaultContext());
    } catch (IOException e) {
      throw Errors.newError(r.defaultContext(), e.getMessage());
    }
  });
  Path file = module.getSource().getFile();
  String fileName = Objects.toString(file, "");
  String dirName = file != null ? Objects.toString(file.getParent(), "") : "";
  return Construct(realm.defaultContext(), moduleConstructor, fileName, dirName);
}

代码示例来源:origin: org.infinispan/infinispan-core

private static synchronized int getHashCodeForSegment(LocalizedCacheTopology cacheTopology, int segment) {
 int numSegments = cacheTopology.getReadConsistentHash().getNumSegments();
 // Caching the hash codes prevents random failures in tests where we create many magic keys
 int[] hcs = hashCodes.computeIfAbsent(numSegments, k -> new int[numSegments]);
 int hc = hcs[segment];
 if (hc != 0) {
   return hc;
 }
 Random r = new Random();
 int attemptsLeft = 100 * numSegments;
 int dummy;
 do {
   dummy = r.nextInt();
   attemptsLeft--;
   if (attemptsLeft < 0) {
    throw new IllegalStateException("Could not find any key in segment " + segment);
   }
 } while (cacheTopology.getSegment(dummy) != segment);
 return hcs[segment] = dummy;
}

代码示例来源:origin: com.conveyal/r5

if (fares == null){
  synchronized (fareSystemCache) {
    FareSystemWrapper fareSystem = fareSystemCache.computeIfAbsent(this.transitLayer,
        BogotaMixedInRoutingFareCalculator::loadFaresFromGTFS);
    this.fares = fareSystem.fares;

代码示例来源:origin: conveyal/r5

if (fares == null){
  synchronized (fareSystemCache) {
    FareSystemWrapper fareSystem = fareSystemCache.computeIfAbsent(this.transitLayer,
        BogotaMixedInRoutingFareCalculator::loadFaresFromGTFS);
    this.fares = fareSystem.fares;

相关文章