Android dalvik system vmruntime

VMRuntime

This class is deprecated.
this is an internal Dalvik class that is not appropriate for general use. It will be removed from the public API in a future release.

Class Overview

Provides an interface to VM-global, Dalvik-specific features. An application cannot create its own Runtime instance, and must obtain one from the getRuntime method.

Summary

Public Methods

public void gcSoftReferences ()

Requests that the virtual machine collect available memory, and collects any SoftReferences that are not strongly-reachable.

public long getExternalBytesAllocated ()

Returns the number of externally-allocated bytes being tracked by trackExternalAllocation/Free().

Returns

public long getMinimumHeapSize ()

Returns the minimum heap size, or zero if no minimum is in effect.

Returns

public static VMRuntime getRuntime ()

Returns the object that represents the VM instance’s Dalvik-specific runtime environment.

Returns

public float getTargetHeapUtilization ()

Gets the current ideal heap utilization, represented as a number between zero and one. After a GC happens, the Dalvik heap may be resized so that (size of live objects) / (size of heap) is equal to this number.

Returns
  • the current ideal heap utilization

public void runFinalizationSync ()

Does not return until any pending finalizers have been called. This may or may not happen in the context of the calling thread. No exceptions will escape.

public synchronized long setMinimumHeapSize (long size)

Sets the desired minimum heap size, and returns the old minimum size. If size is larger than the maximum size, the maximum size will be used. If size is zero or negative, the minimum size constraint will be removed.

Synchronized to make the order of the exchange reliable.

This is only a hint to the garbage collector and may be ignored.

Читайте также:  Умная зарядка для android

Источник

VMRuntime

This class is deprecated.
this is an internal Dalvik class that is not appropriate for general use. It will be removed from the public API in a future release.

Class Overview

Provides an interface to VM-global, Dalvik-specific features. An application cannot create its own Runtime instance, and must obtain one from the getRuntime method.

Summary

Public Methods

public void gcSoftReferences ()

Requests that the virtual machine collect available memory, and collects any SoftReferences that are not strongly-reachable.

public long getExternalBytesAllocated ()

Returns the number of externally-allocated bytes being tracked by trackExternalAllocation/Free().

Returns

public long getMinimumHeapSize ()

Returns the minimum heap size, or zero if no minimum is in effect.

Returns

public static VMRuntime getRuntime ()

Returns the object that represents the VM instance’s Dalvik-specific runtime environment.

Returns

public float getTargetHeapUtilization ()

Gets the current ideal heap utilization, represented as a number between zero and one. After a GC happens, the Dalvik heap may be resized so that (size of live objects) / (size of heap) is equal to this number.

Returns
  • the current ideal heap utilization

public void runFinalizationSync ()

Does not return until any pending finalizers have been called. This may or may not happen in the context of the calling thread. No exceptions will escape.

public synchronized long setMinimumHeapSize (long size)

Sets the desired minimum heap size, and returns the old minimum size. If size is larger than the maximum size, the maximum size will be used. If size is zero or negative, the minimum size constraint will be removed.

Synchronized to make the order of the exchange reliable.

This is only a hint to the garbage collector and may be ignored.

Источник

VMRuntime

Class Overview

Provides an interface to VM-global, Dalvik-specific features. An application cannot create its own Runtime instance, and must obtain one from the getRuntime method.

Summary

Public Methods

public void gcSoftReferences ()

Requests that the virtual machine collect available memory, and collects any SoftReferences that are not strongly-reachable.

public long getExternalBytesAllocated ()

Returns the number of externally-allocated bytes being tracked by trackExternalAllocation/Free().

Returns

public long getMinimumHeapSize ()

Returns the minimum heap size, or zero if no minimum is in effect.

Returns

public static VMRuntime getRuntime ()

Returns the object that represents the VM instance’s Dalvik-specific runtime environment.

Returns

public float getTargetHeapUtilization ()

Gets the current ideal heap utilization, represented as a number between zero and one. After a GC happens, the Dalvik heap may be resized so that (size of live objects) / (size of heap) is equal to this number.

Returns
  • the current ideal heap utilization

public void runFinalizationSync ()

Does not return until any pending finalizers have been called. This may or may not happen in the context of the calling thread. No exceptions will escape.

Читайте также:  Android crop to padding

public synchronized long setMinimumHeapSize (long size)

Sets the desired minimum heap size, and returns the old minimum size. If size is larger than the maximum size, the maximum size will be used. If size is zero or negative, the minimum size constraint will be removed. Synchronized to make the order of the exchange reliable.

Parameters
size the new suggested minimum heap size, in bytes
Returns
  • the old minimum heap size value

public float setTargetHeapUtilization (float newTarget)

Sets the current ideal heap utilization, represented as a number between zero and one. After a GC happens, the Dalvik heap may be resized so that (size of live objects) / (size of heap) is equal to this number.

Источник

VMRuntime

Class Overview

Provides an interface to VM-global, Dalvik-specific features. An application cannot create its own Runtime instance, and must obtain one from the getRuntime method.

Summary

Public Methods

public void gcSoftReferences ()

Requests that the virtual machine collect available memory, and collects any SoftReferences that are not strongly-reachable.

public long getExternalBytesAllocated ()

Returns the number of externally-allocated bytes being tracked by trackExternalAllocation/Free().

Returns

public long getMinimumHeapSize ()

Returns the minimum heap size, or zero if no minimum is in effect.

Returns

public static VMRuntime getRuntime ()

Returns the object that represents the VM instance’s Dalvik-specific runtime environment.

Returns

public float getTargetHeapUtilization ()

Gets the current ideal heap utilization, represented as a number between zero and one. After a GC happens, the Dalvik heap may be resized so that (size of live objects) / (size of heap) is equal to this number.

Returns
  • the current ideal heap utilization

public void runFinalizationSync ()

Does not return until any pending finalizers have been called. This may or may not happen in the context of the calling thread. No exceptions will escape.

public synchronized long setMinimumHeapSize (long size)

Sets the desired minimum heap size, and returns the old minimum size. If size is larger than the maximum size, the maximum size will be used. If size is zero or negative, the minimum size constraint will be removed. Synchronized to make the order of the exchange reliable.

Parameters
size the new suggested minimum heap size, in bytes
Returns
  • the old minimum heap size value

public float setTargetHeapUtilization (float newTarget)

Sets the current ideal heap utilization, represented as a number between zero and one. After a GC happens, the Dalvik heap may be resized so that (size of live objects) / (size of heap) is equal to this number.

Источник

Android SDK: боремся с ограничением размера памяти для картинок

В графическом приложении для рисования используется SurfaceView и пара Bitmap размером с экран (например, я хочу изобразить плавное листание страниц книги).

На многих устройствах с большим разрешением экрана приложение падает c ошибкой
AndroidRuntime: java.lang.OutOfMemoryError: bitmap size exceeds VM budget

Проблема в том, что память для Bitmap, а также для SurfaceView резервируется из общей кучи процесса. Лимит размера кучи — невелик, как правило немногим больше 10Мб. И задается этот лимит при сборке системы.

Попытки улучшить ситуацию урезанием формата пикселя с 32 бит до 16 не слишком помогают. Проблема просто вылезает позже — например, при открытии окна поверх SurfaceView (видимо, при этом создается еще один Bitmap размером с экран).

Ограничение размера графических буферов программы в 3-4 экрана — это до обидного мало! Попробуем исправить такую несправедливость.

На самом деле, большая часть функциональности Bitmap реализована в нативном коде (JNI), и буфер выделяется не в Java Heap, а с помощью обычного сишного malloc. Почему же на него накладываются ограничения общего размера heap?

Оказывается, каждое выделение памяти для Bitmap регистрируется в dalvik.system.VMRuntime c момощью методов trackExternalAllocation / trackExternalFree. Именно метод trackExternalAllocation бросает исключение при попытке выделения памяти сверх лимита.

Что если попытаться обмануть тупого робота? После размещения картинки сказать, что внешняя память, которую только что заняли, уже освобождена. А перед освобождением картинки — имитировать что соответствующий размер памяти только что занят.

Осталось преодолеть небольшую проблему — методы trackExternalAllocation и trackExternalFree не видны. Придется вызывать их «хакерскими» методами — через Reflection.

Пробуем реализовать эту идею.
Создаем пустой проект Android Application.

Для удобства доступ к VMRuntime реализуем в отдельном классе.

Создание/освобождение Bitmap оформим в виде отдельного класса — фабрики.
Здесь же будем запоминать, для каких из битмапов мы поправили информацию о занятой памяти — чтобы не забыть вернуть при освобождении.

Теперь напишем тест, проверяющий, работает ли данный метод. Метод testAllocation() будет пытаться создать максимальное количество мегабайтных картинок (пока не вылетит OutOfMemory или не будет достигнут указанный предел). Флажком useHack задаем запуск теста с хаком или без. Метод возвращает объем, который удалось занять под картинки.

Вызовем тест в Activity.onCreate() — с применением хака и без него.
Результаты покажем на экране и в логе. (Layout «main» нужно поправить — добавить к TextView ID, по которому будем менять текст).

Итак, запускаем и видим результат:
03-07 09:43:37.233: I/bmphack(17873): normally: 10 MB allocated
03-07 09:43:37.233: I/bmphack(17873): with hack: 48 MB allocated

Без хака нам удалось создать всего 10 картинок по 1 мегабайту. С хаком — максимальное количество, которое мы указали (48 мегабайт).
С большими размерами тест все же подвисал на моем симуляторе — после

Надеюсь, кому-то эта статья окажется полезной.

Источник

Читайте также:  Android с хорошей батареей
Оцените статью