putIfAbsent总是返回null

时间:2014-03-27 17:23:08

标签: java multithreading hashmap concurrenthashmap

我正在开发一个wordcount程序,我在其中创建N个线程,每个线程都会收到一个包含许多不同数字的char[]缓冲区,例如[2355 3326 94438 123 123...]我想创建一个地图,其中key是数字本身,值是它出现的时间。我正在从char[]数组转换为整数,如下所示。

然而,似乎每次调用putIfAbsent()时,它总是返回null,这意味着它没有找到该值的键。这没有意义,因为我的文本文件中有数千个重复值。地图应该最终大约300kb,而不是一千兆字节。

newbyte[]char[],仅包含数字和空格

为什么putIfAbsent总是返回null?

另外,当我完成后打印地图时,它看起来像这样:

233303192 = 1
1770057208 = 1
1323329638 = 1
1278321050 = 1
962422124 = 1
472527478 = 1
936125441 = 1
-350637153 = 1
-601349585 = 1

这很奇怪,因为任何输入的最大值是65535.不确定这是否有任何意义。

        public void run() {
            int counter = 0; int i; Integer check;  int j =0; int temp = 0; int intbuilder = 0;
            for (i = 0; i < newbyte.length; i++) {
                    if (newbyte[i] != ' ') { //delimiter is not found, so add to temp char array
                            intbuilder = (intbuilder * 10) + (int)newbyte[i];
                            counter++;
                    }
                    else {    
                            check = wordCountMap.putIfAbsent(intbuilder, 1);
                            if (check != null) { 
                                    wordCountMap.put(intbuilder, check + 1);
                            }
                            intbuilder = 0;

1 个答案:

答案 0 :(得分:0)

问题不在并发哈希映射中。它与您解析字符数组的方式

public void startThreads() throws InterruptedException{
        char[] input = {'1',' ','2',' ','3','4',' ','1',' ','2',' ','3','4',' ','1'};
        Thread workerThread = new Thread(new Worker(input));
        workerThread.start();
        workerThread.join();
        System.out.println("Count for 1 & 2 are "+countMap.get(1)+" and "+countMap.get(2));
    }

    private class Worker implements  Runnable{

        private char[] newbyte;

        public Worker(char[] newbyte){
            this.newbyte = newbyte;
        }

        @Override
        public void run()  {
            int number=0;
            for(int i=0;i< newbyte.length;i++){
                if(newbyte[i] != ' '){
                    number = (number*10)+Character.getNumericValue(newbyte[i]);
                }else{
                    Integer currentValue = countMap.putIfAbsent(number, 1);
                    if(currentValue != null){
                        countMap.put(number, currentValue+1);
                    }
                    number = 0;
                }
            }
            Integer currentValue = countMap.putIfAbsent(number, 1);
            if(currentValue != null){
                countMap.put(number, currentValue+1);
            }

        }

    }