goo blog サービス終了のお知らせ 

タブレット用プログラムの書き止め

android OS & iPadOS の記録。

基礎。スレッドプール考察。

2022-06-17 17:01:20 | Android studio 日記

わからん。
スレッドをキューに溜め込んでいって順番にバックグラウンドで処理をしている。
大雑把に言うと。

その方法の種類が複数ある。
developerは、分かっている人向けの説明で、かつ、抽出説明だから理解できない。

Executorsクラスがあって、その下に複数の継承クラスがある。
developerの説明はホント理解しづらい。


//developer引用。//

public class MyApplication extends Application {
    ExecutorService executorService = Executors.newFixedThreadPool(4);
    executorService.submit( ここに何かを入れる );この表記&説明は無い。上の行のみの記載だった。
}


public class MyApplication extends Application {
    /*
     * Gets the number of available cores
     * (not always the same as the maximum number of cores)
     */
    private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();

    // Instantiates the queue of Runnables as a LinkedBlockingQueue
    private final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();

    // Sets the amount of time an idle thread waits before terminating
    private static final int KEEP_ALIVE_TIME = 1;
    // Sets the Time Unit to seconds
    private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;

    // Creates a thread pool manager
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            NUMBER_OF_CORES,       // Initial pool size
            NUMBER_OF_CORES,       // Max pool size
            KEEP_ALIVE_TIME,
            KEEP_ALIVE_TIME_UNIT,
            workQueue
    );
    ...
}

//developer引用ここまで。//


Executors
ExecutorService
ThreadPoolExecutor

これらでスレッドを溜め込んで処理できる。

 

**スレッドプールを使いたい理由**
ディレクトリ内の画像をサムネイル作成&キャッシュファイル保存はスレッド処理では数十枚が限界。
数百枚だとサムネイル表示の待ち時間が長すぎる。

なので、全体を順番に処理するスレッドとrecyclerViewのスライドに合わせて見えている部分を処理するスレッドを同時に動かしたい。
だけど、developerの説明はわからん。ネットワーク処理説明が優先だし。

 

色々検索して、こちらでスレッドプールの説明を読みました。

https*//outofmem.tumblr.com/post/94053254909/android-executor-1
(*→:)

まとめで、AsyncTaskでダメな場合は、そちらを考えるのでもいいんじゃないか。という解説でした。


なんか、AsyncTaskもスレッドプールの機能が備わっているらしい。
API29までの限定アプリにしてしまえという事で、AsyncTaskの封印を解く。


並列処理なのでキャッシュファイル保存で問題が起きるはず。
保存前チェックと破棄、例外処理はキッチリ考える。

また、閲覧場所を固定したので内部ディレクトリは固有キャッシュディレクトリにサムネイルファイルを保存する。
/Removable のディレクトリは、元画像のディレクトリ内にthumbnaile-testディレクトリを作り、そこに保存する。

こんな感じ。