LoginSignup
3
1

More than 1 year has passed since last update.

[Android] Bitmapのrecycle()は何をしているのか

Last updated at Posted at 2022-12-18

Bitmapの処理を行なっているライブラリのコードを読むと、Bitmapのrecycle()メソッドが呼ばれていることに気づく。そこで、Bitmapのrecycle()の挙動について調べたので、以下にまとめる。

AndroidバージョンごとのBitmapのメモリ管理の違い

前提知識として、以下の公式ドキュメントによれば、Bitmapのメモリ管理の方法は、Androidのバージョンによって異なる。

まず、Android 2.2 (API level 8) 以下では、GCが発生する際に、アプリのスレッドが停止される。一方、Android 2.3でconcurrent GCが追加され、Bitmapへの参照が無くなった直後に、メモリが回収されるようになった。

また、Android 2.3.3 (API level 10) 以下では、Bitmapのピクセルデータはネイティブメモリに保存される一方で、Bitmap自体はDalvik (JVM) 側のヒープ領域に保存される。これにより、ネイティブメモリに保存されたピクセルデータは自動で解放されず、OOMやクラッシュの原因となることがある。
ゆえに、Android 2.3.3 (API level 10) 以下では、recycle()を呼び出すことで、メモリを解放することが推奨されている。

Android 3.0 (API level 11) からAndroid 7.1 (API level 25) では、ピクセルデータはBitmapと併せて、Dalvikのヒープ領域に保存される。Android 8.0 (API level 26) 以降では、ピクセルデータはネイティブヒープに保存される。

Bitmapのrecycle()は何をしているのか

以下の公式ドキュメントを参考に、実際にrecycle()が何をしているのかを記載する。

Free the native object associated with this bitmap, and clear the reference to the pixel data.

Bitmapに関連づけられたネイティブ側のオブジェクトを解放し、ピクセルデータへの参照を除外する。

This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references.

これは、ピクセルデータを同期的には解放しない。すなわち、他に参照がない場合に限り、ガーベジコレクションされることを許可するのみである。

The bitmap is marked as "dead", meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing.

recycle()が呼ばれると、そのBitmapは"dead"としてマークされる。そうなると、getPixels()setPixels()等のメソッドが呼ばれた際に例外を投げるようになり、何も描画しない。

This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap.

recycle()の操作は不可逆的なものである。つまり、そのBitmapをこの先使用しない場合に限って呼び出されるべきである。

This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap.

これは高度な操作で、通常呼ぶ必要はない。なぜならば、通常のGCの処理によって、Bitmapへの参照が無くなった時点で、メモリが解放されるからである。

上記のように、recycle()のドキュメントにおいては、Android 3.0以降を想定しているからか、通常recycle()を呼ぶ必要はないとしている。

その他の参考記事

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1