简体   繁体   English

使用 ConcurrentHashMap 的线程安全

[英]Threadsafe with ConcurrentHashMap

I have an issue on which I need to run .register at most one time on a multi-threaded env, so i tried to use ConcurrentHashMap but seems like its not thread-safe or I'm using it correctly我有一个问题,我需要在多线程环境中最多运行.register一次,所以我尝试使用 ConcurrentHashMap 但似乎它不是线程安全的或者我正在正确使用它

object NonFunctionalMetrics {

  val histograms = new ConcurrentHashMap[String, Histogram](10).asScala
  def workerProcessingHistogram(name: String): Histogram = {
    val histogramName = s"${prefix}_${name.toSnakeCase}_processing_time"
    histograms.getOrElseUpdate(
                              key = histogramName,
                              op = Histogram.build(histogramName, s"${name} worker processing time in microseconds")
                                .labelNames("status")
                                .linearBuckets(config.service.metrics.http.histogramStart, config.service.metrics.http.histogramWidth, config.service.metrics.http.histogramCount)
                                .register()
    )
  }
}

throws me exception抛出异常

Collector already registered that provides name: my_app_new_site_exclusion_worker_processing_time_count

on:在:

    val onSuccessHistogram: Histogram.Child = NonFunctionalMetrics.workerProcessingHistogram(worker.name).labelSuccess()
    val onFailureHistogram: Histogram.Child = NonFunctionalMetrics.workerProcessingHistogram(worker.name).labelFailure()

When I'm adding synchronized its working greats, as follows:当我添加synchronized它的工作伟人时,如下所示:

 def workerProcessingHistogram(name: String): Histogram = synchronized {
    val histogramName = s"${prefix}_${name.toSnakeCase}_processing_time"
    histograms.getOrElseUpdate(
                              key = histogramName,
                              op = Histogram.build(histogramName, s"${name} worker processing time in microseconds")
                                .labelNames("status")
                                .linearBuckets(config.service.metrics.http.histogramStart, config.service.metrics.http.histogramWidth, config.service.metrics.http.histogramCount)
                                .register()
    )
  }

I saw that the get(key) two threads are getting false answer and create the histogram with register - doesn't the ConcurrentHashMap need to handle those scenarios?我看到get(key)两个线程得到false答案并使用register创建直方图 - ConcurrentHashMap 不需要处理这些场景吗?

You could use computeIfAbsent on the underlying Java ConcurrentHashMap.您可以在底层 Java ConcurrentHashMap 上使用computeIfAbsent But getOrElseUpdate on a ConcurrentMap returned by .asScala will use the non-concurrent implementation of mutable Map in Scala.但是getOrElseUpdate返回的 ConcurrentMap 上的.asScala将使用 Scala 中可变 Map 的非并发实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM