1. 场景说明
现有一个 10g 文件的数据,里面包含了 18-70 之间的整数,分别表示 18-70 岁的人群数量统计。假设年龄范围分布均匀,分别表示系统中所有用户的年龄数,找出重复次数最多的那个数,现有一台内存为 4g、2 核 cpu 的电脑,请写一个算法实现。
23,31,42,19,60,30,36,........
2. 模拟数据
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(); } } }
上述代码调整参数执行 2 次,凑 10g 数据在 d 盘 user.dat 文件里:
准备好 10g 数据后,接着写如何处理这些数据。
3. 场景分析
10g 的数据比当前拥有的运行内存大的多,不能全量加载到内存中读取。如果采用全量加载,那么内存会直接爆掉,只能按行读取。java 中的 bufferedreader 的 readline() 按行读取文件里的内容。
4. 读取数据
首先,我们写一个方法单线程读完这 30 亿数据需要多少时间,每读 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(); }
按行读完 10g 的数据大概 20 秒,基本每 100 行,1 亿多数据花 1 秒,速度还挺快。
5. 处理数据
5.1 思路一
通过单线程处理,初始化一个 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(); } }
单线程读取并统计 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(); } }
通过比较找出年龄数最多的年龄并打印出来:
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); }
完整代码
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); } }
测试结果
总共花了 3 分钟读取完并统计完所有数据。
内存消耗为 2g-2.5g,cpu 利用率太低,只向上浮动了 20%-25% 之间。
要想提高 cpu 利用率,那么可以使用多线程去处理。
下面我们使用多线程去解决这个 cpu 利用率低的问题。
5.2 思路二:分治法
使用多线程去消费读取到的数据。 采用生产者、消费者模式去消费数据。
因为在读取的时候是 比较快的,单线程的数据处理能力比较差。因此思路一的性能阻塞在取数据的一方且又是同步操作,导致整个链路的性能会变的很差。
所谓分治法就是分而治之,也就是说将海量数据分割处理。 根据 cpu 的能力初始化 n 个线程,每一个线程去消费一个队列,这样线程在消费的时候不会出现抢占队列的问题。同时为了保证线程安全和生产者消费者模式的完整,采用阻塞队列。java 中提供了 linkedblockingqueue 就是一个阻塞队列。
初始化阻塞队列
使用 linkedlist 创建一个阻塞队列列表:
private static list<linkedblockingqueue<string>> blockqueuelists = new linkedlist<>();
在 static 块里初始化阻塞队列的数量和单个阻塞队列的容量为 256。
上面讲到了 30 亿数据大概 2500 行,按行塞到队列里。20 个队列,那么每个队列 125 个,因此可以容量可以设计为 256 即可。
//每个队列容量为256 for (int i = 0; i < threadnums; i++) { blockqueuelists.add(new linkedblockingqueue<>(256)); }
生产者
为了实现负载的功能,首先定义一个 count 计数器,用来记录行数:
private static atomiclong count = new atomiclong(0);
按照行数来计算队列的下标 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(); } }
消费者
1) 队列线程私有化
消费方在启动线程的时候根据 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(); } }
2) 多子线程分割字符串
由于从队列中多到的字符串非常的庞大,如果又是用单线程调用 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(); } }
3) 分割字符串算法
分割时从 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); }
完整代码
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(); } } }
测试结果
内存和 cpu 初始占用大小:
启动后,运行时内存稳定在 11.7g,cpu 稳定利用在 90% 以上。
总耗时由 180 秒缩减到 103 秒,效率提升 75%,得到的结果也与单线程处理的一致。
6. 遇到的问题
如果在运行了的时候,发现 gc 突然罢工不工作了,有可能是 jvm 的堆中存在的垃圾太多,没回收导致内存的突增。
解决方法
在读取一定数量后,可以让主线程暂停几秒,手动调用 gc。
到此这篇关于如何用 java 几分钟处理完 30 亿个数据的文章就介绍到这了,更多相关java 处理数据内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!