最近做平板应用,需要做一个循环扫描局域网IP端口的功能,实现原理是开一个线程池,然后将250个ping的线程加入其中开始运行,部分代码如下:
new Thread(new Runnable() {
@Override
public void run() {
int threadNum = 250;
ExecutorService executor = Executors.newFixedThreadPool(threadNum);
for (int i = 0; i < threadNum; i++) {
executor.execute(new PingRunner());
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
executor.shutdown();
try {
while (!tpe.isTerminated()) {
while (!executor.isTerminated()) {
Thread.sleep(200);
}
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "Fetched num is " + fetchedNum);
EventUtil.post(new IPMessage("DONE", true));
if (mIPSearchThread != null) mIPSearchThread.stop();
DeInit();
}
}).start();
在其他机型上运行都无异常,华为设备上已有三例不同型号的设备出现OOM,具体异常如下:
java.lang.OutOfMemoryError: pthread_create (1040KB stack) failed: Out of memory
at java.lang.Thread.nativeCreate(Native Method)
at java.lang.Thread.start(Thread.java:745)
at cn.moonmark.longyang.exhibition.utils.IPScanner.scan(IPScanner.java:394)
at cn.moonmark.longyang.exhibition.ui.activity.MainActivity.scanIP(MainActivity.java:143)
at cn.moonmark.longyang.exhibition.ui.activity.MainActivity.connSocket(MainActivity.java:
at cn.moonmark.longyang.exhibition.ui.activity.MainActivity.onCreate(MainActivity.java:83
at android.app.Activity.performCreate(Activity.java:6910)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2746)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6585)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
于是百度一番,看到早有大神发现了这一点,https://www.jianshu.com/p/e574f0ffdb42,这里懂了大概就是线程并发的猫腻了
再输入"华为 内存 "哦不,“华为 OOM 线程”,原来也有人研究过这个了:
早有华为魅族这些优秀的厂商把可控线程数控制在500到3000个,非常好!
问题发现了,也需要解决吧,明显代码是有漏洞的,怎样尽量少的不碰触500的红线呢,尽量让自己的程序处理好并发吧,原先的
Executors.newFixedThreadPool()
需要换掉,换成ThreadPoolExecutor
之后,基本稳了。
ThreadPoolExecutor tpe = new ThreadPoolExecutor(20,
threadNum,
1000 * 2,
TimeUnit.MILLISECONDS,
workQueue);
for (int i = 0; i < threadNum; i++) {
tpe.execute(new PingRunner());
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
tpe.shutdown();
try {
while (!tpe.isTerminated()) {
Thread.sleep(200);
}
} catch (Exception e) {
e.printStackTrace();
}
ThreadPoolExecutor的五参构造函数:
- corePoolSize 核心线程数大小,当线程数 < corePoolSize ,会创建线程执行 runnable
- maximumPoolSize 最大线程数, 当线程数 >= corePoolSize的时候,会把 runnable 放入 workQueue中
- keepAliveTime 保持存活时间,当线程数大于corePoolSize的空闲线程能保持的最大时间。
- unit 时间单位
- workQueue 保存任务的阻塞队列
改动也不大