Android 棧記憶體溢位bug fix小記(pthread_create (1040KB stack) failed: Out of memory)

BryceLee發表於2019-01-24

錯誤日誌:

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:753)
    at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:970)
    at java.util.concurrent.ThreadPoolExecutor.ensurePrestart(ThreadPoolExecutor.java:1611)
    at java.util.concurrent.ScheduledThreadPoolExecutor.delayedExecute(ScheduledThreadPoolExecutor.java:342)
    at java.util.concurrent.ScheduledThreadPoolExecutor.schedule(ScheduledThreadPoolExecutor.java:579)
    at java.util.concurrent.ScheduledThreadPoolExecutor.submit(ScheduledThreadPoolExecutor.java:680)
    at io.reactivex.internal.schedulers.NewThreadWorker.a(NewThreadWorker.java:145)
    at io.reactivex.internal.schedulers.IoScheduler$EventLoopWorker.a(IoScheduler.java:231)
    at io.reactivex.Scheduler$Worker.a(Scheduler.java:371)複製程式碼
    由日誌可以看出這是由Rxjava2內部,往執行緒池中新增任務,所報出的棧記憶體溢位。
本人使用的Rxjava2 (版本是2.2.2);執行緒呼叫器使用的Scheduler.io()通過檢視
    public static Scheduler io() {
    return RxJavaPlugins.onIoScheduler(IO);
    } 
    -->
    public static Scheduler onIoScheduler(@NonNull Scheduler defaultScheduler) {
    Function<? super Scheduler, ? extends Scheduler> f = onIoHandler;
    if (f == null) {
        return defaultScheduler;
    }
    return apply(f, defaultScheduler);
    }
    -->預設的排程器就是IO:
     IO = RxJavaPlugins.initIoScheduler(new IOTask());
    -->通過IOTask():
    static final class IoHolder {
    static final Scheduler DEFAULT = new IoScheduler();
    }
    -->IoScheduler()內部:
    CachedWorkerPool(long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) {
        this.keepAliveTime = unit != null ? unit.toNanos(keepAliveTime) : 0L;
        this.expiringWorkerQueue = new ConcurrentLinkedQueue<ThreadWorker>();
        this.allWorkers = new CompositeDisposable();
        this.threadFactory = threadFactory;

        ScheduledExecutorService evictor = null;
        Future<?> task = null;
        if (unit != null) {
            evictor = Executors.newScheduledThreadPool(1, EVICTOR_THREAD_FACTORY);
            task = evictor.scheduleWithFixedDelay(this, this.keepAliveTime, this.keepAliveTime, TimeUnit.NANOSECONDS);
        }
        evictorService = evictor;
        evictorTask = task;
    }
    -->可以發現是通過Executors.newScheduledThreadPool(1, EVICTOR_THREAD_FACTORY)來構造執行緒池;
    -->:
    public ScheduledThreadPoolExecutor(int corePoolSize,
                                   ThreadFactory threadFactory) {
    super(corePoolSize, Integer.MAX_VALUE,
          DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue(), threadFactory);
    }
    -->可以看到最大執行緒數是無限大的;預設保活時間是10秒。
    -->所以,當你頻繁使用Rxjava2的Scheduler.io()來執行任務,
    可能會出現棧記憶體溢位的情況。特別是一些華為手機。通過Android Profilter觀察CPU使用情況,就可以發現大量的執行緒被建立,
    而且沒有被及時殺死。
複製程式碼

解決方案:

自定義Schedulers的執行緒池,在頻繁使用Rxjava2的時候僅使用單個呼叫度的例項。 例如:

    if (scheduler==null){
    scheduler = Schedulers.from(Executors.newFixedThreadPool(10));
    }
    observable.subscribeOn(scheduler)
                    .unsubscribeOn(scheduler)
                    .observeOn(AndroidSchedulers.mainThread())
複製程式碼

相關文章