首页 \ 问答 \ Java ConcurrentHashMap损坏了值(Java ConcurrentHashMap corrupt values)

Java ConcurrentHashMap损坏了值(Java ConcurrentHashMap corrupt values)

我有一个ConcurrentHashMap,有时表现出奇怪的行为。

当我的应用程序第一次启动时,我从文件系统中读取一个目录,并使用文件名作为键将每个文件的内容加载到ConcurrentHashMap中。 某些文件可能为空,在这种情况下,我将值设置为“空”。

一旦加载了所有文件,工作线程池将等待外部请求。 当请求进来时,我调用getData()函数,在那里我检查ConcurrentHashMap是否包含密钥。 如果密钥存在,我得到值并检查值是否为“空”。 如果value.contains(“empty”),我返回“找不到文件”。 否则,返回文件的内容。 当密钥不存在时,我尝试从文件系统加载该文件。

private String getData(String name) {
    String reply = null;
    if (map.containsKey(name)) {
        reply = map.get(name);
    } else {
        reply = getDataFromFileSystem(name);
    }

    if (reply != null && !reply.contains("empty")) {
        return reply;
    }

    return "file not found";
}

有时,ConcurrentHashMap将返回非空文件的内容(即value.contains("empty") == false ),但是行:

if (reply != null && !reply.contains("empty")) 

返回FALSE。 我将IF语句分为两部分: if (reply != null)if (!reply.contains("empty")) 。 IF语句的第一部分返回TRUE。 第二部分返回FALSE。 所以我决定打印出变量“reply”,以确定字符串的内容是否确实包含“empty”。 这不是这种情况,即内容不包含字符串“empty”。 此外,我添加了这条线

int indexOf = reply.indexOf("empty");

由于变量回复在我打印出来时不包含字符串“empty”,因此我期望indexOf返回-1。 但是函数返回的值大约是字符串的长度,即if reply.length == 15100 ,则reply.indexOf("empty")返回15099。

我每周都会遇到这个问题,每周大约2-3次。 此过程每天重新启动,因此会定期重新生成ConcurrentHashMap。

有没有人在使用Java的ConcurrentHashMap时看到过这样的行为?

编辑

private String getDataFromFileSystem(String name) {
    String contents = "empty";
    try {
        File folder = new File(dir);

        File[] fileList = folder.listFiles();
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isFile() && fileList[i].getName().contains(name)) {
                String fileName = fileList[i].getAbsolutePath();

                FileReader fr = null;
                BufferedReader br = null;

                try {
                    fr = new FileReader(fileName);
                    br = new BufferedReader(fr);
                    String sCurrentLine;
                    while ((sCurrentLine = br.readLine()) != null) {
                        contents += sCurrentLine.trim();
                    }
                    if (contents.equals("")) {
                        contents = "empty";
                    }

                    return contents;
                } catch (Exception e) {
                    e.printStackTrace();

                    if (contents.equals("")) {
                        contents = "empty";
                    }
                    return contents;
                } finally {
                    if (fr != null) {
                        try {
                            fr.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (br != null) {
                        try {
                            br.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (map.containsKey(name)) {
                        map.remove(name);
                    }

                    map.put(name, contents);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();

        if (contents.equals("")) {
            contents = "empty";
        }
        return contents;
    }
    return contents;
}

I have a ConcurrentHashMap that exhibits strange behavior on occasion.

When my app first starts up, I read a directory from the file system and load contents of each file into the ConcurrentHashMap using the filename as the key. Some files may be empty, in which case I set the value to "empty".

Once all files have been loaded, a pool of worker threads will wait for external requests. When a request comes in, I call the getData() function where I check if the ConcurrentHashMap contains the key. If the key exists I get the value and check if the value is "empty". If value.contains("empty"), I return "file not found". Otherwise, the contents of the file is returned. When the key does not exist, I try to load the file from the file system.

private String getData(String name) {
    String reply = null;
    if (map.containsKey(name)) {
        reply = map.get(name);
    } else {
        reply = getDataFromFileSystem(name);
    }

    if (reply != null && !reply.contains("empty")) {
        return reply;
    }

    return "file not found";
}

On occasion, the ConcurrentHashMap will return the contents of a non-empty file (i.e. value.contains("empty") == false), however the line:

if (reply != null && !reply.contains("empty")) 

returns FALSE. I broke down the IF statement into two parts: if (reply != null) and if (!reply.contains("empty")). The first part of the IF statement returns TRUE. The second part returns FALSE. So I decided to print out the variable "reply" in order to determine if the contents of the string does in fact contain "empty". This was NOT the case i.e. the contents did not contain the string "empty". Furthermore, I added the line

int indexOf = reply.indexOf("empty");

Since the variable reply did not contain the string "empty" when I printed it out, I was expecting indexOf to return -1. But the function returned a value approx the length of the string i.e. if reply.length == 15100, then reply.indexOf("empty") was returning 15099.

I experience this issue on a weekly basis, approx 2-3 times a week. This process is restarted on a daily basis therefore the ConcurrentHashMap is re-generated regularly.

Has anyone seen such behavior when using Java's ConcurrentHashMap?

EDIT

private String getDataFromFileSystem(String name) {
    String contents = "empty";
    try {
        File folder = new File(dir);

        File[] fileList = folder.listFiles();
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isFile() && fileList[i].getName().contains(name)) {
                String fileName = fileList[i].getAbsolutePath();

                FileReader fr = null;
                BufferedReader br = null;

                try {
                    fr = new FileReader(fileName);
                    br = new BufferedReader(fr);
                    String sCurrentLine;
                    while ((sCurrentLine = br.readLine()) != null) {
                        contents += sCurrentLine.trim();
                    }
                    if (contents.equals("")) {
                        contents = "empty";
                    }

                    return contents;
                } catch (Exception e) {
                    e.printStackTrace();

                    if (contents.equals("")) {
                        contents = "empty";
                    }
                    return contents;
                } finally {
                    if (fr != null) {
                        try {
                            fr.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (br != null) {
                        try {
                            br.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (map.containsKey(name)) {
                        map.remove(name);
                    }

                    map.put(name, contents);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();

        if (contents.equals("")) {
            contents = "empty";
        }
        return contents;
    }
    return contents;
}

原文:https://stackoverflow.com/questions/11401197
更新时间:2022-03-30 16:03

最满意答案

你可以设置谷歌地图的样式。

以下示例将所有地图要素变为灰色,然后将动脉道路几何体以蓝色着色,并完全隐藏商业标签

  var styleArray = [
  {
    featureType: "all",
    stylers: [
      { saturation: -80 }
    ]
  },{
    featureType: "road.arterial",
    elementType: "geometry",
    stylers: [
      { hue: "#00ffee" },
      { saturation: 50 }
    ]
  },{
    featureType: "poi.business",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  }
];

有关详细信息,请参阅此链接


You can style google maps.

The following example turns all map features to gray, then colors arterial road geometry in blue, and hides business labels completely

  var styleArray = [
  {
    featureType: "all",
    stylers: [
      { saturation: -80 }
    ]
  },{
    featureType: "road.arterial",
    elementType: "geometry",
    stylers: [
      { hue: "#00ffee" },
      { saturation: 50 }
    ]
  },{
    featureType: "poi.business",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  }
];

Please refer this link for detailed info

相关问答

更多
  • 如果您希望标记可见,则需要设置其map属性: for (var n = 0; n < this.markers.length; n++) { var marker = this.markers[n]; var distance = google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(), location) / 1609; if (distance > radius) { // 4 Marker ...
  • 确保包含Google Maps Javascript API(我假设您已经这样做了): JS: var map; var geocoder; function initialize() { var mapOptions = { center: new g ...
  • 如果将display none设置为sidebar-wrapper元素,则可以看到它们。 您的地图宽度为100%,符号+和 - 位于侧边栏后面。 只是尝试调整这些元素的位置(例如,减小地图的大小),它会起作用。 If you set display none to the sidebar-wrapper element you can see them. Your map width is 100% and the symbols + and - are behind your sidebar. Just ...
  • 您也可以下载KML等地图,下载网址类似 https://www.google.com/maps/d/kml?mid=themymaps.mapid 它没有记录,但是当我使用这个URL创建一个KmlLayer的时候它现在对我很有用(只要它们没有修改下载过程,它就会工作)。 示例( 原始地图 ) function initialize() { var map = new google.maps.Map(document.getElementById('map-canvas'), { zo ...
  • 你可以设置谷歌地图的样式。 以下示例将所有地图要素变为灰色,然后将动脉道路几何体以蓝色着色,并完全隐藏商业标签 var styleArray = [ { featureType: "all", stylers: [ { saturation: -80 } ] },{ featureType: "road.arterial", elementType: "geometry", stylers: [ { hue: "#00ffe ...
  • 我最终这样做的方法是在labelContent属性中添加丰富的HTML,通过labelClass在其上设置一个类,然后将icon设置为透明( https://maps.gstatic.com/mapfiles/transparent.png ) 这样,实际图标是不可见的,但您可以通过标签创建丰富的HTML / CSS标记。 这并没有破坏群集器的功能 The way I ended up doing this was to put in rich HTML into the labelContent prop ...
  • 我不确定你想要加载到legend框中但是这可能有帮助吗? 您似乎希望使用与用户点击的event的数据更新legend 。 您应该能够在现有的listener执行此操作,如: document.getElementById('legend').textContent = 'Mag Type: ' + event.feature.getProperty('magType'); 希望这是有帮助的,但它可能完全取决于您的目标! 更新: 是的,您提供的图例是图像。 如果您愿意使用图像,只需将图像包含在图例div中, ...
  • 瓷砖覆盖完全符合我的要求。 我不得不生成切片并覆盖tile url提供程序以从磁盘而不是url加载图像。 Tile overlays does exactly what I asked. I had to generate tiles and also override the tile url provider to load the images from disk instead of url.
  • 我相信您需要与Google取得联系才能获得Maps API。 我不认为他们只是让街上的任何人拥有它。 http://support.google.com/enterprisehelp/bin/request.py?contact_type=maps_engine&hl=en I believe you will need to get in touch with Google to receive a Maps API. I don't think they just let anyone on the s ...
  • 通过使用GoogleMap.setMapType(MAP_TYPE_NONE),您将获得一张空地图。 使用我在这个SO问题的答案中描述的CanvasTileProvider,然后你可以在瓷砖中绘制任何东西。 By using GoogleMap.setMapType(MAP_TYPE_NONE) you will get an empty map. Using e.g. the CanvasTileProvider I have described in the answer to this SO ques ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)