java.util.concurrent.ConcurrentHashMap Java Examples

The following examples show how to use java.util.concurrent.ConcurrentHashMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractClassLoaderValue.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Associates given value {@code v} with this ClassLoaderValue and given
 * ClassLoader and returns {@code null} if there was no previously associated
 * value or does nothing and returns previously associated value if there
 * was one.
 *
 * @param cl the ClassLoader for the associated value
 * @param v  the value to associate
 * @return previously associated value or null if there was none
 */
public V putIfAbsent(ClassLoader cl, V v) {
    ConcurrentHashMap<CLV, Object> map = map(cl);
    @SuppressWarnings("unchecked")
    CLV clv = (CLV) this;
    while (true) {
        try {
            Object val = map.putIfAbsent(clv, v);
            return extractValue(val);
        } catch (Memoizer.RecursiveInvocationException e) {
            // propagate RecursiveInvocationException for the same key that
            // is just being calculated in computeIfAbsent
            throw e;
        } catch (Throwable t) {
            // don't propagate exceptions thrown from foreign Memoizer -
            // pretend that there was no entry and retry
            // (foreign computeIfAbsent invocation will try to remove it anyway)
        }
        // TODO:
        // Thread.onSpinLoop(); // when available
    }
}
 
Example #2
Source File: AppCacheService.java    From radar with Apache License 2.0 6 votes vote down vote up
public synchronized void initApp() {
	synchronized (lockObj) {
		Transaction transaction = Tracer.newTransaction("AppCache", "initApp");
		try {
			isReinit = true;
			List<AppEntity> appEntities = appRepository.findAll();
			Map<String, AppDto> servMap = doUpdateCache(appEntities);
			Map<String, AppDto> servMap1 = new ConcurrentHashMap<>(servMap);
			appRefMap.set(servMap1);
			log.info("App 初始化完成!");
			initServCounter.inc();
			isReinit = false;
			transaction.setStatus(Transaction.SUCCESS);
		} catch (Exception e) {
			transaction.setStatus(e);
		} finally {
			transaction.complete();
		}
	}
}
 
Example #3
Source File: MapWithCollisionsProviders.java    From streamsupport with GNU General Public License v2.0 6 votes vote down vote up
private static <T> Collection<Object[]> makeMapsMoreTypes(String desc,
                                                          T[] keys,
                                                          T val) {
    Collection<Object[]> cases = new ArrayList<>();
    cases.add(createCase("Hashtable with " + desc,
                         new Hashtable<>(), keys, val));
    cases.add(createCase("IdentityHashMap with " + desc,
                         new IdentityHashMap<>(), keys, val));
    cases.add(createCase("TreeMap with " + desc,
                         new TreeMap<>(), keys, val));
    cases.add(createCase("WeakHashMap with " + desc,
                         new WeakHashMap<>(), keys, val));
    cases.add(createCase("ConcurrentHashMap with " + desc,
                         new ConcurrentHashMap<>(), keys, val));
    cases.add(createCase("ConcurrentSkipListMap with " + desc,
                         new ConcurrentSkipListMap<>(), keys, val));
    return cases;
}
 
Example #4
Source File: DistinctEntrySetElements.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final ConcurrentHashMap<String, String> concurrentHashMap =
        new ConcurrentHashMap<>();

    concurrentHashMap.put("One", "Un");
    concurrentHashMap.put("Two", "Deux");
    concurrentHashMap.put("Three", "Trois");

    Set<Map.Entry<String, String>> entrySet = concurrentHashMap.entrySet();
    HashSet<Map.Entry<String, String>> hashSet = new HashSet<>(entrySet);

    if (false == hashSet.equals(entrySet)) {
        throw new RuntimeException("Test FAILED: Sets are not equal.");
    }
    if (hashSet.hashCode() != entrySet.hashCode()) {
        throw new RuntimeException("Test FAILED: Set's hashcodes are not equal.");
    }
}
 
Example #5
Source File: TCMazeHandler.java    From Gadomancy with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Map<CellLoc, Short> calculateCellLocs(WorldServer world) {
    ConcurrentHashMap<CellLoc, Short> oldDat = MazeHandler.labyrinth;
    ConcurrentHashMap<CellLoc, Short> bufferOld = new ConcurrentHashMap<CellLoc, Short>(labyrinthCopy);
    MazeHandler.labyrinth = labyrinthCopy;
    int chX = getHighestPossibleRandWH(); //To ensure we're always +x and +z
    int chZ = getHighestPossibleRandWH();
    int w = randWH(world.rand);
    int h = randWH(world.rand);
    while (MazeHandler.mazesInRange(chX, chZ, w, h)) {
        chX++; //We grow the mazes in +x direction!
    }
    MazeThread mt = new MazeThread(chX, chZ, w, h, world.rand.nextLong());
    mt.run();
    Map<CellLoc, Short> locs = calculateDifferences(bufferOld);
    labyrinthCopy = MazeHandler.labyrinth;
    MazeHandler.labyrinth = oldDat;
    return locs;
}
 
Example #6
Source File: Configuration.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
/**
 * Load a class by name.
 *
 * @param name the class name.
 * @return the class object.
 * @throws ClassNotFoundException if the class is not found.
 */
public Class<?> getClassByName(String name) throws ClassNotFoundException {
    Map<String, Class<?>> map = CACHE_CLASSES.get(classLoader);
    if (map == null) {
        Map<String, Class<?>> newMap = new ConcurrentHashMap<>();
        map = CACHE_CLASSES.putIfAbsent(classLoader, newMap);
        if (map == null) {
            map = newMap;
        }
    }

    Class clazz = map.get(name);
    if (clazz == null) {
        clazz = Class.forName(name, true, classLoader);
        if (clazz != null) {
            map.put(name, clazz);
        }
    }

    return clazz;
}
 
Example #7
Source File: TXManagerImpl.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor that implements the {@link CacheTransactionManager} interface.
 * Only only one instance per {@link com.gemstone.gemfire.cache.Cache}
 */
public TXManagerImpl(CachePerfStats cachePerfStats, LogWriterI18n logWriter,
    GemFireCacheImpl cache) {
  this.cache = cache;
  this.dm = cache.getDistributedSystem().getDistributionManager();
  this.cachePerfStats = cachePerfStats;
  this.logWriter = logWriter;
  this.hostedTXStates = new CustomEntryConcurrentHashMap<TXId, TXStateProxy>(
      128, CustomEntryConcurrentHashMap.DEFAULT_LOAD_FACTOR,
      TXMAP_CONCURRENCY);
  this.suspendedTXs = new ConcurrentHashMap<TXId, TXStateInterface>();
  this.finishedTXStates = new TXFinishedMap(cache.getDistributedSystem(),
      cache.getCancelCriterion());
  this.waitMap = new ConcurrentHashMap<TransactionId, Queue<Thread>>();
  this.expiryTasks = new ConcurrentHashMap<TransactionId, SystemTimerTask>();
}
 
Example #8
Source File: RestLookupService.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void setAuthenticator(OkHttpClient.Builder okHttpClientBuilder, ConfigurationContext context) {
    final String authUser = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_USERNAME).evaluateAttributeExpressions().getValue());
    this.basicUser = authUser;


    isDigest = context.getProperty(PROP_DIGEST_AUTH).asBoolean();
    final String authPass = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_PASSWORD).evaluateAttributeExpressions().getValue());
    this.basicPass = authPass;
    // If the username/password properties are set then check if digest auth is being used
    if (!authUser.isEmpty() && isDigest) {

        /*
         * OkHttp doesn't have built-in Digest Auth Support. A ticket for adding it is here[1] but they authors decided instead to rely on a 3rd party lib.
         *
         * [1] https://github.com/square/okhttp/issues/205#issuecomment-154047052
         */
        final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
        com.burgstaller.okhttp.digest.Credentials credentials = new com.burgstaller.okhttp.digest.Credentials(authUser, authPass);
        final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);

        okHttpClientBuilder.interceptors().add(new AuthenticationCacheInterceptor(authCache));
        okHttpClientBuilder.authenticator(new CachingAuthenticatorDecorator(digestAuthenticator, authCache));
    }
}
 
Example #9
Source File: CodeSystemsCache.java    From FHIR with Apache License 2.0 6 votes vote down vote up
/**
 * Determines and reports any discrepancies between the current thread's Code Systems cache and the contents of the database CODE_SYSTEMS table.
 * @param dao A Parameter DAO instance
 * @return String - A report detailing cache/db discrepancies.
 */
public static String reportCacheDiscrepancies(ParameterDAO dao) {
    
    String tenantDatstoreCacheName = getCacheNameForTenantDatastore();
    Map<String, Integer> dbMap;
    ConcurrentHashMap<String,Integer> cachedMap = codeSystemIdMaps.get(tenantDatstoreCacheName);
    String discrepancies = "";
    
    if (enabled) {
        try {
            dbMap = dao.readAllCodeSystems();
            discrepancies = CacheUtil.reportCacheDiscrepancies("CodeSystemsCache", cachedMap, dbMap);
        } 
        catch (FHIRPersistenceDBConnectException | FHIRPersistenceDataAccessException e) {
            log.log(Level.SEVERE, "Failure obtaining  all code systems." , e);
            discrepancies = CacheUtil.NEWLINE + "Could not report on CodeSystems cache discrepancies." + CacheUtil.NEWLINE;
        }
    }
    
    return discrepancies;
}
 
Example #10
Source File: StyleParser.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
/**
* spits input string, converts keys and values to lower case, and replaces '"'
* and ''' if any
*
* @param style the input style string
* @return the sanitised map
*/
  public static Map<String, String> splitIntoMap(final String style) {
      final ConcurrentHashMap<String, String> retVal = new ConcurrentHashMap<>();
      if (style == null) {
          return retVal;
      }

      final String[] keyVals = AT_LEAST_ONE_WHITESPACE_PATTERN.matcher(style.toLowerCase(Locale.UK)).replaceAll("").split(";");
      for (final String keyVal : keyVals) {
          final String[] parts = STYLE_ASSIGNMENT_PATTERN.split(keyVal, 2);
          if (parts.length <= 1) {
              continue;
          }

          retVal.put(parts[0], QUOTES_PATTERN.matcher(parts[1]).replaceAll(""));
      }

      return retVal;
  }
 
Example #11
Source File: NatsDispatcher.java    From nats.java with Apache License 2.0 5 votes vote down vote up
NatsDispatcher(NatsConnection conn, MessageHandler handler) {
    super(conn);
    this.defaultHandler = handler;
    this.incoming = new MessageQueue(true);
    this.subscriptionsUsingDefaultHandler = new ConcurrentHashMap<>();
    this.subscriptionsWithHandlers = new ConcurrentHashMap<>();
    this.subscriptionHandlers = new ConcurrentHashMap<>();
    this.running = new AtomicBoolean(false);
    this.waitForMessage = Duration.ofMinutes(5); // This can be long since we aren't doing anything
}
 
Example #12
Source File: BasicCloner.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * Initialise a set of built in CloneImplementors for commonly used JDK types
 */
private void initializeBuiltInImplementors() {
	builtInImplementors.put(ArrayList.class, new ArrayListImplementor());
	builtInImplementors.put(ConcurrentHashMap.class, new ConcurrentHashMapImplementor());
	builtInImplementors.put(GregorianCalendar.class, new GregorianCalendarImplementor());
	builtInImplementors.put(HashMap.class, new HashMapImplementor());
	builtInImplementors.put(HashSet.class, new HashSetImplementor());
	builtInImplementors.put(LinkedList.class, new LinkedListImplementor());
	builtInImplementors.put(TreeMap.class, new TreeMapImplementor());
	allImplementors.putAll(builtInImplementors);
}
 
Example #13
Source File: PlatformDependent.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new fastest {@link ConcurrentMap} implementaion for the current platform.
 */
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(int initialCapacity) {
    if (CAN_USE_CHM_V8) {
        return new ConcurrentHashMapV8<K, V>(initialCapacity);
    } else {
        return new ConcurrentHashMap<K, V>(initialCapacity);
    }
}
 
Example #14
Source File: Store.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
public Store(String cStorePath, int cSize, String lStorePath, int lSize) {
    this.cStorePath = cStorePath;
    this.cSize = cSize;
    this.lStorePath = lStorePath;
    this.lSize = lSize;
    mapedFileQueue = new MapedFileQueue(cStorePath, cSize, null);
    consumeQueueTable =
            new ConcurrentHashMap<String/* topic */, ConcurrentHashMap<Integer/* queueId */, ConsumeQueue>>();
}
 
Example #15
Source File: LambdaProxyHandlerTest.java    From aws-lambda-proxy-java with MIT License 5 votes vote down vote up
@Test
public void corsSupportShouldReturnAccessControlAllowOriginHeaderFromMethodHandler() throws Exception {
    LambdaProxyHandler<Configuration> handlerWithCORSSupport = new TestLambdaProxyHandler(true);
    String someHeader = "someHeader";
    String someValue = "someValue";
    Map<String, String> requestHeaders = new ConcurrentHashMap<>();
    requestHeaders.put(CONTENT_TYPE, CONTENT_TYPE_1.toString());
    requestHeaders.put(ACCEPT, ACCEPT_TYPE_1.toString());
    requestHeaders.put(someHeader, someValue);
    ApiGatewayProxyRequest request = new ApiGatewayProxyRequestBuilder()
            .withHttpMethod(METHOD)
            .withHeaders(requestHeaders)
            .withContext(context)
            .build();
    Map<String, String> responseHeaders = new ConcurrentHashMap<>();
    responseHeaders.put(someHeader, someValue);
    String accessControlAllowOriginKey = "Access-Control-Allow-Origin";
    String accessControlAllowOriginValue = "*";
    when(methodHandler.handle(request, singletonList(CONTENT_TYPE_1), singletonList(ACCEPT_TYPE_1), context))
            .thenReturn(new ApiGatewayProxyResponse.ApiGatewayProxyResponseBuilder()
                    .withStatusCode(OK.getStatusCode())
                    .withHeaders(responseHeaders)
                    .build());
    handlerWithCORSSupport.registerMethodHandler(METHOD, c -> methodHandler);

    ApiGatewayProxyResponse response = handlerWithCORSSupport.handleRequest(request, context);

    assertThat(response).isNotNull();
    assertThat(response.getHeaders()).containsKey(accessControlAllowOriginKey);
    assertThat(response.getHeaders().get(accessControlAllowOriginKey)).isEqualTo(accessControlAllowOriginValue);
}
 
Example #16
Source File: DeletedBlockLogImpl.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public DeletedBlockLogImpl(ConfigurationSource conf,
                           ContainerManager containerManager,
                           SCMMetadataStore scmMetadataStore) {
  maxRetry = conf.getInt(OZONE_SCM_BLOCK_DELETION_MAX_RETRY,
      OZONE_SCM_BLOCK_DELETION_MAX_RETRY_DEFAULT);
  this.containerManager = containerManager;
  this.scmMetadataStore = scmMetadataStore;
  this.lock = new ReentrantLock();

  // transactionToDNsCommitMap is updated only when
  // transaction is added to the log and when it is removed.

  // maps transaction to dns which have committed it.
  transactionToDNsCommitMap = new ConcurrentHashMap<>();
}
 
Example #17
Source File: InMemoryMetricsRepository.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void save(MetricEntity entity) {
    if (entity == null || StringUtil.isBlank(entity.getApp())) {
        return;
    }
    allMetrics.computeIfAbsent(entity.getApp(), e -> new ConcurrentHashMap<>(16))
        .computeIfAbsent(entity.getResource(), e -> new ConcurrentLinkedHashMap.Builder<Long, MetricEntity>()
            .maximumWeightedCapacity(MAX_METRIC_LIVE_TIME_MS).weigher((key, value) -> {
                // Metric older than {@link #MAX_METRIC_LIVE_TIME_MS} will be removed.
                int weight = (int)(System.currentTimeMillis() - key);
                // weight must be a number greater than or equal to one
                return Math.max(weight, 1);
            }).build()).put(entity.getTimestamp().getTime(), entity);
}
 
Example #18
Source File: ConcurrentHashMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Cannot create with only negative capacity
 */
public void testConstructor1() {
    try {
        new ConcurrentHashMap(-1);
        shouldThrow();
    } catch (IllegalArgumentException success) {}
}
 
Example #19
Source File: FileFontStrike.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
Rectangle2D.Float getGlyphOutlineBounds(int glyphCode) {

        if (boundsMap == null) {
            boundsMap = new ConcurrentHashMap<Integer, Rectangle2D.Float>();
        }

        Integer key = Integer.valueOf(glyphCode);
        Rectangle2D.Float bounds = boundsMap.get(key);

        if (bounds == null) {
            bounds = fileFont.getGlyphOutlineBounds(pScalerContext, glyphCode);
            boundsMap.put(key, bounds);
        }
        return bounds;
    }
 
Example #20
Source File: EventSourceSyncDurationLogger.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Autowired
public EventSourceSyncDurationLogger(final Optional<List<EventSource>> eventSources) {
    allChannels = eventSources.orElse(Collections.emptyList())
            .stream()
            .map(EventSource::getChannelName)
            .collect(toSet());
    healthyChannels = ConcurrentHashMap.newKeySet();
}
 
Example #21
Source File: CacheSupportImpl.java    From jim-framework with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void initialize() {
	cacheToInvocationsMap = new ConcurrentHashMap<String, Set<CachedInvocation>>(cacheManager.getCacheNames().size());
	for (final String cacheName : cacheManager.getCacheNames()) {
		cacheToInvocationsMap.put(cacheName, new CopyOnWriteArraySet<CachedInvocation>());
	}
}
 
Example #22
Source File: StateMachine.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
public State(Fsm fsm) {
    this.fsm = fsm;

    ConcurrentHashMap<Class<?>, Method> handlerCache = stateCaches.get(getClass());
    if (handlerCache == null) {
        handlerCache = new ConcurrentHashMap<>();
        ConcurrentHashMap<Class<?>, Method> old = stateCaches.putIfAbsent(getClass(), handlerCache);
        if (old != null) {
            handlerCache = old;
        }
    }
    this.handlerCache = handlerCache;
}
 
Example #23
Source File: SoftRefLogWriter.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
public SoftRefLogWriter(StatLogWriter nestLog){
    this.map = new ConcurrentHashMap<LogKey, Reference<LogCounter>>( // NL
    1024,
        0.75f,
        32);
    this.nestLog = nestLog;
    schdeuleFlush();
}
 
Example #24
Source File: WorldGen.java    From TFC2 with GNU General Public License v3.0 5 votes vote down vote up
public WorldGen(World w) 
{
	world = w;
	islandCache = Collections.synchronizedMap(new ConcurrentHashMap<Integer, CachedIsland>());
	mapQueue = new PriorityBlockingQueue<Integer>();
	buildThreads = new ThreadBuild[TFCOptions.maxThreadsForIslandGen];
	EMPTY_MAP = new IslandMap(ISLAND_SIZE, 0);
	IslandParameters ip = createParams(0, -2, 0);
	ip.setIslandTemp(ClimateTemp.TEMPERATE);
	ip.setIslandMoisture(Moisture.HIGH);
	EMPTY_MAP.newIsland(ip);
	EMPTY_MAP.generateFake();
}
 
Example #25
Source File: DatabaseStringCodecImpl.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@Override
public Integer findId(String stringType, String value) {

    ConcurrentHashMap<String, Integer> typeValue2Key = vale2KeyMapping.computeIfAbsent(stringType, key->new ConcurrentHashMap<>());
    int resultKey = typeValue2Key.computeIfAbsent(value, k->getOrInsertId(stringType,value));
    return resultKey;
}
 
Example #26
Source File: PingClient.java    From tchannel-java with MIT License 5 votes vote down vote up
public void run() throws Exception {
    TChannel tchannel = new TChannel.Builder("ping-client").build();
    SubChannel subChannel = tchannel.makeSubChannel("ping-server");
    final ConcurrentHashMap<String, AtomicInteger> msgs = new ConcurrentHashMap<>();
    final CountDownLatch done = new CountDownLatch(requests);

    for (int i = 0; i < requests; i++) {
        JsonRequest<Ping> request = new JsonRequest.Builder<Ping>("ping-server", "ping")
            .setBody(new Ping("{'key': 'ping?'}"))
            .setHeader("some", "header")
            .setTimeout(100 + i)
            .build();
        TFuture<JsonResponse<Pong>> f = subChannel.send(
                request,
                InetAddress.getByName(host),
                port
            );

        f.addCallback(new TFutureCallback<JsonResponse<Pong>>() {
            @Override
            public void onResponse(JsonResponse<Pong> pongResponse) {
                done.countDown();
                String msg = pongResponse.toString();
                AtomicInteger count = msgs.putIfAbsent(msg, new AtomicInteger(1));
                if (count != null) {
                    count.incrementAndGet();
                }
            }
        });
    }

    done.await();
    for (Map.Entry<String, AtomicInteger> stringIntegerEntry : msgs.entrySet()) {
        System.out.println(String.format("%s%n\tcount:%s",
            stringIntegerEntry.getKey(), stringIntegerEntry.getValue()
        ));
    }

    tchannel.shutdown(false);
}
 
Example #27
Source File: SchemaVersionInfoCache.java    From registry with Apache License 2.0 5 votes vote down vote up
public SchemaVersionInfoCache(final SchemaVersionRetriever schemaRetriever,
                              final int schemaCacheSize,
                              final long schemaCacheExpiryInMilliSecs) {
    idWithNameVersion = new ConcurrentHashMap<>(schemaCacheSize);
    nameVersionWithIds = new ConcurrentHashMap<>(schemaCacheSize);
    loadingCache = createLoadingCache(schemaRetriever, schemaCacheSize, schemaCacheExpiryInMilliSecs);
}
 
Example #28
Source File: NMTokenSecretManagerInRM.java    From big-c with Apache License 2.0 5 votes vote down vote up
public NMTokenSecretManagerInRM(Configuration conf) {
  this.conf = conf;
  timer = new Timer();
  rollingInterval = this.conf.getLong(
      YarnConfiguration.RM_NMTOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS,
      YarnConfiguration.DEFAULT_RM_NMTOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS)
      * 1000;
  // Add an activation delay. This is to address the following race: RM may
  // roll over master-key, scheduling may happen at some point of time, an
  // NMToken created with a password generated off new master key, but NM
  // might not have come again to RM to update the shared secret: so AM has a
  // valid password generated off new secret but NM doesn't know about the
  // secret yet.
  // Adding delay = 1.5 * expiry interval makes sure that all active NMs get
  // the updated shared-key.
  this.activationDelay =
      (long) (conf.getLong(YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS,
          YarnConfiguration.DEFAULT_RM_NM_EXPIRY_INTERVAL_MS) * 1.5);
  LOG.info("NMTokenKeyRollingInterval: " + this.rollingInterval
      + "ms and NMTokenKeyActivationDelay: " + this.activationDelay
      + "ms");
  if (rollingInterval <= activationDelay * 2) {
    throw new IllegalArgumentException(
        YarnConfiguration.RM_NMTOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS
            + " should be more than 3 X "
            + YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS);
  }
  appAttemptToNodeKeyMap =
      new ConcurrentHashMap<ApplicationAttemptId, HashSet<NodeId>>();
}
 
Example #29
Source File: LocalJobStore.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Override
public void addCounts(UUID jobId, Map<String, Integer> newCounts) {
  if (newCounts == null) {
    return;
  }

  newCounts.forEach(
      (dataName, dataCount) ->
          counts
              .computeIfAbsent(jobId, k -> new ConcurrentHashMap<>())
              .merge(dataName, dataCount, Integer::sum));
}
 
Example #30
Source File: PerfHashBenchmark.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  while( !_start ) {
    try { Thread.sleep(1); } catch( Exception e ){}
  }

  long nano1 = System.nanoTime();

  int total = 0;
  if( _read_ratio == 0 ) {
    total = run_churn();
  } else {
    if( _hash instanceof ConcurrentLinkedHashMap) {
      total = run_normal( (ConcurrentLinkedHashMap<String,String>) _hash);
    } else if( _hash instanceof NonBlockingHashMap ) {
      total = run_normal( (NonBlockingHashMap<String,String>) _hash);
    } else if( _hash instanceof ConcurrentHashMap ) {
      total = run_normal( (ConcurrentHashMap<String,String>) _hash);
    } else {
      total = run_normal(_hash);
    }
  }

  _ops[_tnum] = total;
  long nano2 = System.nanoTime();
  _nanos[_tnum] = (nano2-nano1);
}