日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

一、場景說明

現有一個10G文件的數據,里面包含了18-70之間的整數,分別表示18-70歲的人群數量統計,假設年齡范圍分布均勻,分別表示系統中所有用戶的年齡數,找出重復次數最多的那個數,現有一臺內存為4G、2核CPU的電腦,請寫一個算法實現。

 

23,31,42,19,60,30,36,........

 

二、模擬數據

 

JAVA中一個整數占4個字節,模擬10G為30億左右個數據, 采用追加模式寫入10G數據到硬盤里。

 

每100萬個記錄寫一行,大概4M一行,10G大概2500行數據。

 

package bigdata;

import java.io.*;
import java.util.Random;

/**
 * @Desc:
 * @Author: bingbing
 * @Date: 2022/5/4 0004 19:05
 */
public class GenerateData {
    private static Random random = new Random();


    public static int generateRandomData(int start, int end) {
        return random.nextInt(end - start + 1) + start;
    }


    /**
     * 產生10G的 1-1000的數據在D盤
     */
    public void generateData() throws IOException {
        File file = new File("D:\ User.dat");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int start = 18;
        int end = 70;
        long startTime = System.currentTimeMillis();
        BufferedWriter bos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
        for (long i = 1; i < Integer.MAX_VALUE * 1.7; i++) {
            String data = generateRandomData(start, end) + ",";
            bos.write(data);
            // 每100萬條記錄成一行,100萬條數據大概4M
            if (i % 1000000 == 0) {
                bos.write("n");
            }
        }
        System.out.println("寫入完成! 共花費時間:" + (System.currentTimeMillis() - startTime) / 1000 + " s");
        bos.close();
    }


    public static void main(String[] args) {
        GenerateData generateData = new GenerateData();
        try {
            generateData.generateData();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

上述代碼調整參數執行2次, 湊10個G的數據在D盤的User.dat文件里:

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 


海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

 

 

準備好10G數據后,接著寫如何處理這些數據

 

三、場景分析

 

10G的數據比當前擁有的運行內存大的多,不能全量加載到內存中讀取,如果采用全量加載,那么內存會直接爆掉,只能按行讀取,Java中的bufferedReader的readLine()按行讀取文件里的內容。

 

四、讀取數據

 

首先我們寫一個方法單線程讀完這30E數據需要多少時間,每讀100行打印一次:

 

    private static void readData() throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME), "utf-8"));
        String line;
        long start = System.currentTimeMillis();
        int count = 1;
        while ((line = br.readLine()) != null) {
            // 按行讀取
//            SplitData.splitLine(line);
            if (count % 100 == 0) {
                System.out.println("讀取100行,總耗時間: " + (System.currentTimeMillis() - start) / 1000 + " s");
                System.gc();
            }
            count++;
        }
        running = false;
        br.close();

    }

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

按行讀完10G的數據大概20秒,基本每100行,1E多數據花1S,速度還挺快:

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 


海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

?

 

五、處理數據

 

思路一

 

通過單線程處理,初始化一個countMap, key為年齡,value為出現的次數, 將每行讀取到的數據按照"," 進行分割,然后獲取到的每一項進行保存到countMap里,如果存在,那么值key的value+1。

 

    for (int i = start; i <= end; i++) {
            try {
                File subFile = new File(dir + "\" + i + ".dat");
                if (!file.exists()) {
                    subFile.createNewFile();
                }
                countMap.computeIfAbsent(i + "", integer -> new AtomicInteger(0));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

單線程讀取并統計countMap:

 

     public static void splitLine(String lineData) {
            String[] arr = lineData.split(",");
            for (String str : arr) {
                if (StringUtils.isEmpty(str)) {
                    continue;
                }
                countMap.computeIfAbsent(str, s -> new AtomicInteger(0)).getAndIncrement();
            }
        }

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

通過比較找出年齡數最多的年齡并打印出來:

 

  private static void findMostAge() {
        Integer targetValue = 0;
        String targetKey = null;
        Iterator<Map.Entry<String, AtomicInteger>> entrySetIterator = countMap.entrySet().iterator();
        while (entrySetIterator.hasNext()) {
            Map.Entry<String, AtomicInteger> entry = entrySetIterator.next();
            Integer value = entry.getValue().get();
            String key = entry.getKey();
            if (value > targetValue) {
                targetValue = value;
                targetKey = key;
            }
        }
        System.out.println("數量最多的年齡為:" + targetKey + "數量為:" + targetValue);
    }

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

完整代碼

 

package bigdata;

import org.Apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @Desc:
 * @Author: bingbing
 * @Date: 2022/5/4 0004 19:19
 * 單線程處理
 */
public class HandleMaxRepeatProblem_v0 {

    public static final int start = 18;
    public static final int end = 70;

    public static final String dir = "D:\dataDir";

    public static final String FILE_NAME = "D:\ User.dat";


    /**
     * 統計數量
     */
    private static Map<String, AtomicInteger> countMap = new ConcurrentHashMap<>();


    /**
     * 開啟消費的標志
     */
    private static volatile boolean startConsumer = false;

    /**
     * 消費者運行保證
     */
    private static volatile boolean consumerRunning = true;


    /**
     * 按照 "," 分割數據,并寫入到countMap里
     */
    static class SplitData {

        public static void splitLine(String lineData) {
            String[] arr = lineData.split(",");
            for (String str : arr) {
                if (StringUtils.isEmpty(str)) {
                    continue;
                }
                countMap.computeIfAbsent(str, s -> new AtomicInteger(0)).getAndIncrement();
            }
        }


    }

    /**
     *  init map
     */

    static {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdir();
        }


        for (int i = start; i <= end; i++) {
            try {
                File subFile = new File(dir + "\" + i + ".dat");
                if (!file.exists()) {
                    subFile.createNewFile();
                }
                countMap.computeIfAbsent(i + "", integer -> new AtomicInteger(0));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {


        new Thread(() -> {
            try {
                readData();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }).start();


    }


    private static void readData() throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME), "utf-8"));
        String line;
        long start = System.currentTimeMillis();
        int count = 1;
        while ((line = br.readLine()) != null) {
            // 按行讀取,并向map里寫入數據
            SplitData.splitLine(line);
            if (count % 100 == 0) {
                System.out.println("讀取100行,總耗時間: " + (System.currentTimeMillis() - start) / 1000 + " s");
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count++;
        }
        findMostAge();

        br.close();
    }

    private static void findMostAge() {
        Integer targetValue = 0;
        String targetKey = null;
        Iterator<Map.Entry<String, AtomicInteger>> entrySetIterator = countMap.entrySet().iterator();
        while (entrySetIterator.hasNext()) {
            Map.Entry<String, AtomicInteger> entry = entrySetIterator.next();
            Integer value = entry.getValue().get();
            String key = entry.getKey();
            if (value > targetValue) {
                targetValue = value;
                targetKey = key;
            }
        }
        System.out.println("數量最多的年齡為:" + targetKey + "數量為:" + targetValue);
    }

    private static void clearTask() {
        // 清理,同時找出出現字符最大的數
        findMostAge();
        System.exit(-1);
    }


}

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

測試結果

 

總共花了3分鐘讀取完并統計完所有數據:

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 


海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

? 內存消耗為2G-2.5G, CPU利用率太低,只向上浮動了20%-25%之間:

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 


海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

?

 

要想提高CPU的利用率,那么可以使用多線程去處理。

 

下面我們使用多線程去解決這個CPU利用率低的問題

 

思路二分治法

 

使用多線程去消費讀取到的數據。 采用生產者、消費者模式去消費數據,因為在讀取的時候是比較快的,單線程的數據處理能力比較差,因此思路一的性能阻塞在取數據方,又是同步的,所以導致整個鏈路的性能會變的很差。

 

所謂分治法就是分而治之,也就是說將海量數據分割處理。 根據CPU的能力初始化n個線程,每一個線程去消費一個隊列,這樣線程在消費的時候不會出現搶占隊列的問題,同時為了保證線程安全和生產者消費者模式的完整,采用阻塞隊列,Java中提供了LinkedBlockingQueue就是一個阻塞隊列。

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 


海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

?

 

初始化阻塞隊列

 

使用linkedList創建一個阻塞隊列列表:

 

    private static List<LinkedBlockingQueue<String>> blockQueueLists = new LinkedList<>();

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

在static塊里初始化阻塞隊列的數量和單個阻塞隊列的容量為256, 上面講到了30E數據大概2500行,按行塞到隊列里,20個隊列,那么每個隊列125個,因此可以容量可以設計為256即可:

 

    //每個隊列容量為256
        for (int i = 0; i < threadNums; i++) {
            blockQueueLists.add(new LinkedBlockingQueue<>(256));
        }

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

生產者

 

為了實現負載的功能, 首先定義一個count計數器,用來記錄行數:

 

    private static AtomicLong count = new AtomicLong(0);

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

按照行數來計算隊列的下標: long index=count.get()%threadNums。 下面算法就實現了對隊列列表中的隊列進行輪詢的投放:

 

   static class SplitData {

        public static void splitLine(String lineData) {
//            System.out.println(lineData.length());
            String[] arr = lineData.split("n");
            for (String str : arr) {
                if (StringUtils.isEmpty(str)) {
                    continue;
                }
                long index = count.get() % threadNums;
                try {
                    // 如果滿了就阻塞
                    blockQueueLists.get((int) index).put(str);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count.getAndIncrement();

            }
        }

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

消費者

 

隊列線程私有化

 

消費方在啟動線程的時候根據index去獲取到指定的隊列,這樣就實現了隊列的線程私有化。

 

    private static void startConsumer() throws FileNotFoundException, UnsupportedEncodingException {
        //如果共用一個隊列,那么線程不宜過多,容易出現搶占現象
        System.out.println("開始消費...");
        for (int i = 0; i < threadNums; i++) {
            final int index = i;
            // 每一個線程負責一個queue,這樣不會出現線程搶占隊列的情況。
            new Thread(() -> {
                while (consumerRunning) {
                    startConsumer = true;
                    try {
                        String str = blockQueueLists.get(index).take();
                        countNum(str);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }


    }

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

多子線程分割字符串

 

由于從隊列中多到的字符串非常的龐大,如果又是用單線程調用split(",")去分割,那么性能同樣會阻塞在這個地方。

 

    // 按照arr的大小,運用多線程分割字符串
    private static void countNum(String str) {
        int[] arr = new int[2];
        arr[1] = str.length() / 3;
//        System.out.println("分割的字符串為start位置為:" + arr[0] + ",end位置為:" + arr[1]);
        for (int i = 0; i < 3; i++) {
            final String innerStr = SplitData.splitStr(str, arr);
//            System.out.println("分割的字符串為start位置為:" + arr[0] + ",end位置為:" + arr[1]);
            new Thread(() -> {
                String[] strArray = innerStr.split(",");
                for (String s : strArray) {
                    countMap.computeIfAbsent(s, s1 -> new AtomicInteger(0)).getAndIncrement();
                }
            }).start();
        }
    }

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

分割字符串算法

 

分割時從0開始,按照等分的原則,將字符串n等份,每一個線程分到一份。

 

用一個arr數組的arr[0] 記錄每次的分割開始位置, arr[1] 記錄每次分割的結束位置,如果遇到的開始的字符不為",", 那么就startIndex-1, 如果結束的位置不為",", 那么將endIndex向后移一位。

 

如果endIndex超過了字符串的最大長度,那么就把最后一個字符賦值給arr[1]。

 

        /**
         * 按照 x坐標 來分割 字符串,如果切到的字符不為“,”, 那么把坐標向前或者向后移動一位。
         *
         * @param line
         * @param arr  存放x1,x2坐標
         * @return
         */
        public static String splitStr(String line, int[] arr) {

            int startIndex = arr[0];
            int endIndex = arr[1];
            char start = line.charAt(startIndex);
            char end = line.charAt(endIndex);
            if ((startIndex == 0 || start == ',') && end == ',') {
                arr[0] = endIndex + 1;
                arr[1] = arr[0] + line.length() / 3;
                if (arr[1] >= line.length()) {
                    arr[1] = line.length() - 1;
                }
                return line.substring(startIndex, endIndex);
            }

            if (startIndex != 0 && start != ',') {
                startIndex = startIndex - 1;
            }

            if (end != ',') {
                endIndex = endIndex + 1;
            }

            arr[0] = startIndex;
            arr[1] = endIndex;
            if (arr[1] >= line.length()) {
                arr[1] = line.length() - 1;
            }
            return splitStr(line, arr);
        }

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

完整代碼

 

package bigdata;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Desc:
 * @Author: bingbing
 * @Date: 2022/5/4 0004 19:19
 * 多線程處理
 */
public class HandleMaxRepeatProblem {

    public static final int start = 18;
    public static final int end = 70;

    public static final String dir = "D:\dataDir";

    public static final String FILE_NAME = "D:\ User.dat";

    private static final int threadNums = 20;


    /**
     * key 為年齡,  value為所有的行列表,使用隊列
     */
    private static Map<Integer, Vector<String>> valueMap = new ConcurrentHashMap<>();


    /**
     * 存放數據的隊列
     */
    private static List<LinkedBlockingQueue<String>> blockQueueLists = new LinkedList<>();


    /**
     * 統計數量
     */
    private static Map<String, AtomicInteger> countMap = new ConcurrentHashMap<>();


    private static Map<Integer, ReentrantLock> lockMap = new ConcurrentHashMap<>();

    // 隊列負載均衡
    private static AtomicLong count = new AtomicLong(0);

    /**
     * 開啟消費的標志
     */
    private static volatile boolean startConsumer = false;

    /**
     * 消費者運行保證
     */
    private static volatile boolean consumerRunning = true;


    /**
     * 按照 "," 分割數據,并寫入到文件里
     */
    static class SplitData {

        public static void splitLine(String lineData) {
//            System.out.println(lineData.length());
            String[] arr = lineData.split("n");
            for (String str : arr) {
                if (StringUtils.isEmpty(str)) {
                    continue;
                }
                long index = count.get() % threadNums;
                try {
                    // 如果滿了就阻塞
                    blockQueueLists.get((int) index).put(str);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count.getAndIncrement();

            }
        }

        /**
         * 按照 x坐標 來分割 字符串,如果切到的字符不為“,”, 那么把坐標向前或者向后移動一位。
         *
         * @param line
         * @param arr  存放x1,x2坐標
         * @return
         */
        public static String splitStr(String line, int[] arr) {

            int startIndex = arr[0];
            int endIndex = arr[1];
            char start = line.charAt(startIndex);
            char end = line.charAt(endIndex);
            if ((startIndex == 0 || start == ',') && end == ',') {
                arr[0] = endIndex + 1;
                arr[1] = arr[0] + line.length() / 3;
                if (arr[1] >= line.length()) {
                    arr[1] = line.length() - 1;
                }
                return line.substring(startIndex, endIndex);
            }

            if (startIndex != 0 && start != ',') {
                startIndex = startIndex - 1;
            }

            if (end != ',') {
                endIndex = endIndex + 1;
            }

            arr[0] = startIndex;
            arr[1] = endIndex;
            if (arr[1] >= line.length()) {
                arr[1] = line.length() - 1;
            }
            return splitStr(line, arr);
        }


        public static void splitLine0(String lineData) {
            String[] arr = lineData.split(",");
            for (String str : arr) {
                if (StringUtils.isEmpty(str)) {
                    continue;
                }
                int keyIndex = Integer.parseInt(str);
                ReentrantLock lock = lockMap.computeIfAbsent(keyIndex, lockMap -> new ReentrantLock());
                lock.lock();
                try {
                    valueMap.get(keyIndex).add(str);
                } finally {
                    lock.unlock();
                }

//                boolean wait = true;
//                for (; ; ) {
//                    if (!lockMap.get(Integer.parseInt(str)).isLocked()) {
//                        wait = false;
//                        valueMap.computeIfAbsent(Integer.parseInt(str), integer -> new Vector<>()).add(str);
//                    }
//                    // 當前阻塞,直到釋放鎖
//                    if (!wait) {
//                        break;
//                    }
//                }

            }
        }

    }

    /**
     *  init map
     */

    static {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdir();
        }

        //每個隊列容量為256
        for (int i = 0; i < threadNums; i++) {
            blockQueueLists.add(new LinkedBlockingQueue<>(256));
        }


        for (int i = start; i <= end; i++) {
            try {
                File subFile = new File(dir + "\" + i + ".dat");
                if (!file.exists()) {
                    subFile.createNewFile();
                }
                countMap.computeIfAbsent(i + "", integer -> new AtomicInteger(0));
//                lockMap.computeIfAbsent(i, lock -> new ReentrantLock());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {


        new Thread(() -> {
            try {
                // 讀取數據
                readData();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }).start();

        new Thread(() -> {
            try {
                // 開始消費
                startConsumer();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            // 監控
            monitor();
        }).start();


    }


    /**
     * 每隔60s去檢查棧是否為空
     */
    private static void monitor() {
        AtomicInteger emptyNum = new AtomicInteger(0);
        while (consumerRunning) {
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (startConsumer) {
                // 如果所有棧的大小都為0,那么終止進程
                AtomicInteger emptyCount = new AtomicInteger(0);
                for (int i = 0; i < threadNums; i++) {
                    if (blockQueueLists.get(i).size() == 0) {
                        emptyCount.getAndIncrement();
                    }
                }
                if (emptyCount.get() == threadNums) {
                    emptyNum.getAndIncrement();
                    // 如果連續檢查指定次數都為空,那么就停止消費
                    if (emptyNum.get() > 12) {
                        consumerRunning = false;
                        System.out.println("消費結束...");
                        try {
                            clearTask();
                        } catch (Exception e) {
                            System.out.println(e.getCause());
                        } finally {
                            System.exit(-1);
                        }
                    }
                }
            }

        }
    }


    private static void readData() throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME), "utf-8"));
        String line;
        long start = System.currentTimeMillis();
        int count = 1;
        while ((line = br.readLine()) != null) {
            // 按行讀取,并向隊列寫入數據
            SplitData.splitLine(line);
            if (count % 100 == 0) {
                System.out.println("讀取100行,總耗時間: " + (System.currentTimeMillis() - start) / 1000 + " s");
                try {
                    Thread.sleep(1000L);
                    System.gc();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count++;
        }

        br.close();
    }

    private static void clearTask() {
        // 清理,同時找出出現字符最大的數
        Integer targetValue = 0;
        String targetKey = null;
        Iterator<Map.Entry<String, AtomicInteger>> entrySetIterator = countMap.entrySet().iterator();
        while (entrySetIterator.hasNext()) {
            Map.Entry<String, AtomicInteger> entry = entrySetIterator.next();
            Integer value = entry.getValue().get();
            String key = entry.getKey();
            if (value > targetValue) {
                targetValue = value;
                targetKey = key;
            }
        }
        System.out.println("數量最多的年齡為:" + targetKey + "數量為:" + targetValue);
        System.exit(-1);
    }

    /**
     * 使用linkedBlockQueue
     *
     * @throws FileNotFoundException
     * @throws UnsupportedEncodingException
     */
    private static void startConsumer() throws FileNotFoundException, UnsupportedEncodingException {
        //如果共用一個隊列,那么線程不宜過多,容易出現搶占現象
        System.out.println("開始消費...");
        for (int i = 0; i < threadNums; i++) {
            final int index = i;
            // 每一個線程負責一個queue,這樣不會出現線程搶占隊列的情況。
            new Thread(() -> {
                while (consumerRunning) {
                    startConsumer = true;
                    try {
                        String str = blockQueueLists.get(index).take();
                        countNum(str);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }


    }

    // 按照arr的大小,運用多線程分割字符串
    private static void countNum(String str) {
        int[] arr = new int[2];
        arr[1] = str.length() / 3;
//        System.out.println("分割的字符串為start位置為:" + arr[0] + ",end位置為:" + arr[1]);
        for (int i = 0; i < 3; i++) {
            final String innerStr = SplitData.splitStr(str, arr);
//            System.out.println("分割的字符串為start位置為:" + arr[0] + ",end位置為:" + arr[1]);
            new Thread(() -> {
                String[] strArray = innerStr.split(",");
                for (String s : strArray) {
                    countMap.computeIfAbsent(s, s1 -> new AtomicInteger(0)).getAndIncrement();
                }
            }).start();
        }
    }


    /**
     * 后臺線程去消費map里數據寫入到各個文件里, 如果不消費,那么會將內存程爆
     */
    private static void startConsumer0() throws FileNotFoundException, UnsupportedEncodingException {
        for (int i = start; i <= end; i++) {
            final int index = i;
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dir + "\" + i + ".dat", false), "utf-8"));
            new Thread(() -> {
                int miss = 0;
                int countIndex = 0;
                while (true) {
                    // 每隔100萬打印一次
                    int count = countMap.get(index).get();
                    if (count > 1000000 * countIndex) {
                        System.out.println(index + "歲年齡的個數為:" + countMap.get(index).get());
                        countIndex += 1;
                    }
                    if (miss > 1000) {
                        // 終止線程
                        try {
                            Thread.currentThread().interrupt();
                            bw.close();
                        } catch (IOException e) {

                        }
                    }
                    if (Thread.currentThread().isInterrupted()) {
                        break;
                    }


                    Vector<String> lines = valueMap.computeIfAbsent(index, vector -> new Vector<>());
                    // 寫入到文件里
                    try {

                        if (CollectionUtil.isEmpty(lines)) {
                            miss++;
                            Thread.sleep(1000);
                        } else {
                            // 100個一批
                            if (lines.size() < 1000) {
                                Thread.sleep(1000);
                                continue;
                            }
                            // 1000個的時候開始處理
                            ReentrantLock lock = lockMap.computeIfAbsent(index, lockIndex -> new ReentrantLock());
                            lock.lock();
                            try {
                                Iterator<String> iterator = lines.iterator();
                                StringBuilder sb = new StringBuilder();
                                while (iterator.hasNext()) {
                                    sb.Append(iterator.next());
                                    countMap.get(index).addAndGet(1);
                                }
                                try {
                                    bw.write(sb.toString());
                                    bw.flush();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                // 清除掉vector
                                valueMap.put(index, new Vector<>());
                            } finally {
                                lock.unlock();
                            }

                        }
                    } catch (InterruptedException e) {

                    }
                }
            }).start();
        }

    }
}

 

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

測試結果

 

內存和CPU初始占用大小:

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 


海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

?

 

啟動后,運行時穩定在11.7,CPU穩定利用在90%以上。

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 


海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

?

 

總耗時由180S縮減到103S,效率提升75%,得到的結果也與單線程處理的一致!

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 


海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

?

 

遇到的問題

 

如果在運行了的時候,發現GC突然罷工了,開始不工作了,有可能是JVM的堆中存在的垃圾太多,沒回收導致內存的突增。

海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 


海量數據問題:如何用JAVA幾分鐘處理完30億個數據?

 

?

 

解決方法: 在讀取一定數量后,可以讓主線程暫停幾秒,手動調用GC。

 

提示: 本demo的線程創建都是手動創建的,實際開發中使用的是線程池 !~

分享到:
標簽:海量 數據
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定