Quick answer: java.lang.OutOfMemoryError means the Java heap of your app hit its per-app limit, or the runtime could not create a thread. It says nothing about the engine’s native memory, which is where textures, meshes and Unity’s C# heap live. Read the numbers in the message: a huge requested size points at one oversized allocation (a file or image read into a byte[]), a tiny one points at a leak that filled the heap, and pthread_create ... failed points at too many threads or a 32-bit process out of address space.
Games are an odd fit for this error. Most of a game’s memory is native: the engine allocates it outside the Java heap, and when that runs out Android kills the process without throwing anything. So when a game does die with java.lang.OutOfMemoryError, the cause is almost always in the thin Java layer around the engine: a plugin, an ad or analytics SDK, a share or screenshot feature, a WebView, or the JNI calls that pass data between the two worlds. This guide shows how to read the message, how to tell Java memory from native memory with dumpsys meminfo, and how to fix the patterns that fill the Java heap in games.
- The exact error
- Which memory actually ran out
- What causes it in games
- Find which cause you have
- Fix oversized allocations
- Fix leaks in the Java layer
- Fix “pthread_create failed”
- Stopgaps: largeHeap and a 64-bit build
- When the exception is missing: native memory
- What Bugnet sees of an OutOfMemoryError
- Related guides
- Frequently asked questions
The exact error
The heap form, as the Android runtime (ART) prints it (example values, made-up package name, stack trimmed):
E AndroidRuntime: FATAL EXCEPTION: main
E AndroidRuntime: Process: com.studio.mygame, PID: 12300
E AndroidRuntime: java.lang.OutOfMemoryError: Failed to allocate a 33177616 byte allocation with 8388608 free bytes and 21MB until OOM, target footprint 254803968, growth limit 268435456
E AndroidRuntime: at java.util.Arrays.copyOf(Arrays.java:3585)
E AndroidRuntime: at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:211)
E AndroidRuntime: at com.studio.mygame.share.ScreenshotSharer.encode(ScreenshotSharer.java:58)
Older Android versions stop after until OOM; newer ones append the target footprint and the growth limit. The thread form looks like this:
java.lang.OutOfMemoryError: pthread_create (1040KB stack) failed: Try again
at java.lang.Thread.nativeCreate(Native Method)
at java.lang.Thread.start(Thread.java:883)
The ending is the system’s error text: Try again or Out of memory. Just before either exception, logcat has a warning line that starts Throwing OutOfMemoryError and ends with the process’s virtual size (VmSize), which matters for 32-bit builds.
Read the heap message as four numbers:
- The byte allocation is what the code asked for. Here, about 33 MB in one piece.
- Free bytes is unused space inside the heap as it is currently sized.
- Until OOM is how much the heap may still grow before it reaches the limit. The request was larger than that, so it failed.
- Growth limit is the per-app cap in bytes. 268435456 is 256 MB.
A request of tens of megabytes means one allocation was too large. A request of a few hundred bytes with almost nothing left until OOM means the heap was already full, and the line that threw is an innocent bystander.
Which memory actually ran out
An Android game uses several pools of memory, and only one of them throws this exception.
| Pool | What lives there in a game | Limit | What exhaustion looks like |
|---|---|---|---|
| Java heap (ART) | Java and Kotlin objects: plugin code, SDKs, byte[] and String data, arrays passed in through JNI | A fixed per-app cap set by the device maker, often a few hundred megabytes | java.lang.OutOfMemoryError: Failed to allocate ... |
| Native heap | The engine: meshes, audio, physics, Unity’s C# managed heap, bitmap pixel data on Android 8.0 and higher | The device’s RAM | The low memory killer ends the process with no exception, or a native allocation fails and the game aborts |
| Graphics memory | Textures, render targets, buffers | The device’s RAM | Same as native |
| Threads and address space | One stack per thread, about 1 MB each for Java threads | Address space in a 32-bit process; system thread limits | OutOfMemoryError: pthread_create ... failed |
The Java cap is small on purpose. You can read it on a device:
adb shell getprop dalvik.vm.heapgrowthlimit
adb shell getprop dalvik.vm.heapsize
The first value (for example 256m) is the normal limit, the same number ActivityManager.getMemoryClass() reports in megabytes. The second is the limit an app gets with android:largeHeap="true". Both vary by device.
Two things that look similar are different errors. A C# OutOfMemoryException in a Unity game comes from Unity’s managed heap, which is native memory as far as Android is concerned. A game that vanishes with no exception at all was killed by the system for using too much RAM; what happens when a game runs out of memory covers that path.
What causes it in games
- A whole file or download held in a
byte[]orString. Save-file sync, asset downloads, an HTTP response body, a Base64-encoded screenshot. AByteArrayOutputStreamdoubles its buffer as it grows andtoByteArray()copies it again, so a 30 MB payload briefly needs several times that. - Large arrays passed across JNI. When Unity code calls a Java method with a
byte[]argument, the array is copied into a new Java array on the Java heap. Native code that callsNewByteArraydoes the same. - Bitmaps decoded in Java. A 4000 × 3000 photo decoded at full size is 48 MB of pixels. On Android 7.1 and older those pixels are on the Java heap. From Android 8.0 they are native, so they no longer hit the Java cap but still count against the device’s RAM.
- Leaks in the Java layer. Static references to an
Activity, listeners that are registered and never removed, an offline event queue that grows without bound, UnityAndroidJavaObjectinstances that are never disposed and keep their Java objects alive. - SDKs that share your heap. Ad SDKs, WebViews and analytics run in your process and allocate from the same cap. Their objects show up in your heap dump under their package names.
- A thread per task. Code that starts a new
Threadfor every request or event produces thepthread_createform once enough of them are alive at the same time. - A 32-bit build. A 32-bit process has at most 4 GB of address space, and a game can exhaust it long before the device runs out of RAM. Both forms of the error become more likely.
Find which cause you have
Start with the stack trace. The top frames name the allocation that failed, and the first frame from your package or an SDK’s package is where to look. Then measure the pools while the game runs:
adb shell dumpsys meminfo com.studio.mygame
Near the end of the output is an app summary (example values, trimmed):
App Summary
Pss(KB)
------
Java Heap: 231480
Native Heap: 412300
Code: 98112
Stack: 3104
Graphics: 354816
Private Other: 21776
System: 18034
TOTAL PSS: 1139622
Run it a few times: at the menu, in a level, after the action that crashes. Then read it against the limit you printed earlier.
- Java Heap close to the growth limit and climbing across repeated actions: a leak in Java code.
- Java Heap low, then a crash on one action: a single oversized allocation. The requested size in the message confirms it.
- Java Heap low while Native Heap and Graphics are large: the Java heap is not your problem. Either this is the thread form, or the process is being killed for its total size.
For a leak, take a heap dump from a debuggable build (in Unity, a build with Development Build ticked). In Android Studio open View > Tool Windows > Profiler, attach to the game and capture a heap dump from the memory view, or use the command line:
adb shell am dumpheap com.studio.mygame /data/local/tmp/mygame.hprof
adb pull /data/local/tmp/mygame.hprof
Open the file in Android Studio and sort classes by retained size. Look for more than one instance of your Activity, very large byte[] arrays and collections that hold thousands of entries. For the thread form, count threads while the game runs:
adb shell pidof com.studio.mygame
adb shell ps -T -p 12300 | wc -l
A game normally sits at a steady count. A number that keeps rising is the bug.
Fix oversized allocations
Do not hold the whole payload. Stream it in fixed-size chunks:
// Broken: the whole file on the Java heap, and HttpURLConnection
// buffers the body a second time.
byte[] data = Files.readAllBytes(file.toPath());
connection.getOutputStream().write(data);
// Fixed: 64 KB at a time.
connection.setFixedLengthStreamingMode(file.length());
try (InputStream in = new FileInputStream(file);
OutputStream out = connection.getOutputStream()) {
byte[] buffer = new byte[64 * 1024];
int n;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
}
Downsample images to the size you will display. Ask for the dimensions first, then decode at a reduced size:
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, opts);
int sample = 1;
while (opts.outWidth / (sample * 2) >= targetWidth
&& opts.outHeight / (sample * 2) >= targetHeight) {
sample *= 2;
}
opts.inSampleSize = sample;
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, opts);
Across the engine boundary, pass a file path and let each side read it:
// Broken: the PNG is copied into a Java byte[] on the Java heap.
byte[] png = screenshot.EncodeToPNG();
using (var sharer = new AndroidJavaObject("com.studio.mygame.share.ScreenshotSharer"))
{
sharer.Call("share", png);
}
// Fixed: write once, pass a path.
string path = Path.Combine(Application.temporaryCachePath, "share.png");
File.WriteAllBytes(path, screenshot.EncodeToPNG());
using (var sharer = new AndroidJavaObject("com.studio.mygame.share.ScreenshotSharer"))
{
sharer.Call("shareFile", path);
}
Fix leaks in the Java layer
The heap dump tells you which objects are piling up; the fix is to drop the reference that keeps them alive.
// Broken: a static list keeps every Activity that ever registered.
public final class AdEvents {
private static final List<Activity> listeners = new ArrayList<>();
public static void register(Activity a) { listeners.add(a); }
}
// Fixed: unregister when the Activity goes away.
public final class AdEvents {
private static final List<Activity> listeners = new ArrayList<>();
public static void register(Activity a) { listeners.add(a); }
public static void unregister(Activity a) { listeners.remove(a); }
}
@Override
protected void onDestroy() {
AdEvents.unregister(this);
super.onDestroy();
}
Give every cache and queue a maximum size. An analytics queue that stores events while the player is offline should drop the oldest entries past a cap. In Unity, wrap every AndroidJavaObject and AndroidJavaClass in a using block, or call Dispose() on the ones you keep, so the Java objects they reference can be collected. If the dump shows the memory belongs to an SDK’s classes, update the SDK and check that you call its destroy or release methods for banners and web views you no longer show.
Fix “pthread_create failed”
Each Java thread reserves about 1 MB of address space for its stack, which is the 1040KB in the message. A thousand live threads reserve a gigabyte. Replace per-task threads with one shared, bounded pool:
// Broken: one thread per event.
new Thread(() -> upload(event)).start();
// Fixed: four threads for the whole game, created once.
private static final ExecutorService UPLOADS = Executors.newFixedThreadPool(4);
UPLOADS.execute(() -> upload(event));
Check SDK configuration too: some networking and image libraries create a pool per client object, so creating a new client per request multiplies threads. Create one client and reuse it. If the thread count is modest and the warning line shows VmSize near 4 GB, the process is out of address space, which is the 32-bit problem below.
Stopgaps: largeHeap and a 64-bit build
You can ask for the larger Java limit in the manifest:
<application android:largeHeap="true" ... >
In Unity, tick Custom Main Manifest under Player > Publishing Settings > Build and add the attribute in Assets/Plugins/Android/AndroidManifest.xml. Know what you are buying. The larger limit is whatever dalvik.vm.heapsize is on that device, and on some devices it is no larger than the normal one. A bigger heap means longer garbage collections. It does nothing for native memory or for threads. A leak will still fill it, only later. Use it to ship a fix this week while you remove the oversized allocation.
Shipping a 64-bit build is not a stopgap; it removes the address space ceiling. If your game still has a 32-bit-only configuration, the guide to native library ABIs covers how to add arm64 without breaking plugin loading.
When the exception is missing: native memory
If players report the game closing and you find no FATAL EXCEPTION, the process was killed for its total memory use. On Android 11 and higher you can ask the system why recent runs ended:
adb shell dumpsys activity exit-info com.studio.mygame
A low-memory reason there confirms it; the same data is available in code through ActivityManager.getHistoricalProcessExitReasons(). The work is then on the engine side: texture sizes, loaded scenes, asset bundles. Respond to the system’s warning before the kill arrives. Unity raises it as an event:
using UnityEngine;
public class LowMemoryHandler : MonoBehaviour
{
void OnEnable() { Application.lowMemory += OnLowMemory; }
void OnDisable() { Application.lowMemory -= OnLowMemory; }
void OnLowMemory()
{
Debug.LogError("Low memory warning received");
Resources.UnloadUnusedAssets();
}
}
In Java plugin code, release caches in onTrimMemory() and onLowMemory(). To confirm any of these fixes, repeat the action that crashed twenty times in one session and watch dumpsys meminfo: the Java Heap line should return to the same level each time, and the thread count should stay flat. Crashes on low-memory Android devices goes deeper on the native side.
What Bugnet sees of an OutOfMemoryError
An uncaught OutOfMemoryError on a Java thread ends the process, and Bugnet does not capture that: it does not record native crashes or uncaught Java exceptions as stack traces, and a process the system kills for memory never reports at all. Logcat and Play Console’s Android vitals are where those stacks are.
Two cases do reach it. When C# code in a Unity game calls a Java plugin and the plugin throws inside that call, Unity raises an AndroidJavaException in C#, and the Unity SDK files it with recent log lines, game version, OS version and the device’s RAM. And an error you log yourself is filed the same way: the Debug.LogError in the low-memory handler above becomes one grouped entry with an occurrence count, so you can see which devices are warning before they crash. Player-written reports (“it closes when I share a screenshot”) arrive with the same device details. Setup is in getting started.
Related guides
- What Happens When a Game Runs Out of Memory?
- How to Fix a Game Crashing on Low-Memory Android Devices
- How to Fix iOS Jetsam (Out of Memory) Terminations in Your Game
- How to Profile a Unity Game for Memory leaks
- How to Fix “Fatal signal 6 (SIGABRT)” Crashes in an Android Game
Frequently asked questions
What does java.lang.OutOfMemoryError: Failed to allocate mean on Android?
The Java heap of the app could not grow enough to satisfy an allocation without passing its per-app limit. The message gives the size requested, the free space, how far the heap was from the limit, and on newer Android versions the growth limit itself in bytes.
Why does my game get OutOfMemoryError when the phone has plenty of free RAM?
The Java heap has a fixed cap per app that is much smaller than the device's RAM, often a few hundred megabytes. Free RAM on the device does not raise it. The engine's textures and meshes are native memory and are not counted in that cap.
What does pthread_create (1040KB stack) failed: Try again mean?
The runtime could not create a new thread. Either the process has too many threads alive, usually because code starts one per task, or a 32-bit process has run out of address space for another one megabyte stack. Use a bounded thread pool and ship a 64-bit build.
Does android:largeHeap fix OutOfMemoryError?
It raises the Java heap limit to a larger device-defined value, which can hide an oversized allocation for a while. It does not help with leaks, native memory or thread creation, it lengthens garbage collection, and on some devices the larger limit is the same as the normal one.
Why does my Unity game close with no OutOfMemoryError in logcat?
Unity's textures, meshes and C# heap are native memory, so running out of them does not throw a Java exception. Android's low memory killer ends the process instead. Check dumpsys activity exit-info for a low-memory reason and reduce native and graphics memory.
This exception is about the small Java heap, not the engine's memory. Check the requested size in the message and the Java Heap line in dumpsys meminfo before touching your textures.