From 32aa6616044076b3c569a27f873f11695f08887d Mon Sep 17 00:00:00 2001 From: Trustin Lee Date: Wed, 19 Jun 2013 20:41:10 +0900 Subject: [PATCH] Make sure PlatformDependent.maxDirectMemory() works on Android - Fixes #1451 --- .../util/internal/PlatformDependent.java | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/common/src/main/java/io/netty/util/internal/PlatformDependent.java b/common/src/main/java/io/netty/util/internal/PlatformDependent.java index da806c09ae..cc17b97ad3 100644 --- a/common/src/main/java/io/netty/util/internal/PlatformDependent.java +++ b/common/src/main/java/io/netty/util/internal/PlatformDependent.java @@ -23,8 +23,6 @@ import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.InetSocketAddress; @@ -496,10 +494,22 @@ public final class PlatformDependent { // Ignore } - if (maxDirectMemory <= 0) { + if (maxDirectMemory > 0) { + return maxDirectMemory; + } + + try { // Now try to get the JVM option (-XX:MaxDirectMemorySize) and parse it. - RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); - List vmArgs = runtime.getInputArguments(); + // Note that we are using reflection because Android doesn't have these classes. + Class mgmtFactoryClass = Class.forName( + "java.lang.management.ManagementFactory", true, ClassLoader.getSystemClassLoader()); + Class runtimeClass = Class.forName( + "java.lang.management.RuntimeMXBean", true, ClassLoader.getSystemClassLoader()); + + Object runtime = mgmtFactoryClass.getDeclaredMethod("getRuntimeMXBean").invoke(null); + + @SuppressWarnings("unchecked") + List vmArgs = (List) runtimeClass.getDeclaredMethod("getInputArguments").invoke(runtime); for (int i = vmArgs.size() - 1; i >= 0; i --) { Matcher m = MAX_DIRECT_MEMORY_SIZE_ARG_PATTERN.matcher(vmArgs.get(i)); if (!m.matches()) { @@ -520,6 +530,8 @@ public final class PlatformDependent { } break; } + } catch (Throwable t) { + // Ignore } if (maxDirectMemory <= 0) {