Commit adb19b9b authored by Brian Carlstrom's avatar Brian Carlstrom
Browse files

Dalvik is dead, long live Dalvik! DO NOT MERGE

croot
cd libcore
repo start dalvik-is-dead-long-live-dalvik .
repo sync -c .
git rm -r libdvm
git add JavaLibrary.mk (after removing libdvm references, adding explict core-libart references)
git add Docs.mk (after replacing references to libdvm with libart)
git add benchmarks/Android.mk (after adding explict core-libart references)
git add Android.mk (after removing dalvik-host target)
git commit -a -m 'Dalvik is dead, long live Dalvik! DO NOT MERGE'

Bug: 14298175
Change-Id: I0e7a3ce47e0b6e3a7b15006a6d17d103d23e8064
parent 1265f1c7
No related merge requests found
......@@ -50,26 +50,4 @@ $(info * libcore tests are skipped because environment variable LIBCORE_SKIP_TES
$(info ********************************************************************************)
endif
#
# "m dalvik-host" for quick minimal host build
#
.PHONY: dalvik-host
dalvik-host: \
dalvik \
$(HOST_OUT)/bin/dalvikvm \
$(HOST_OUT)/bin/dexopt \
$(HOST_OUT)/lib/libjavacore.so \
$(HOST_OUT)/lib/libjavacrypto.so \
$(HOST_OUT)/lib/libjavacoretests.so \
cacerts-host \
core-hostdex \
conscrypt-hostdex \
okhttp-hostdex \
bouncycastle-hostdex \
apache-xml-hostdex \
apache-harmony-tests-hostdex \
$(call intermediates-dir-for,JAVA_LIBRARIES,core-tests,,COMMON)/classes.jar
include $(subdir_makefiles)
......@@ -17,8 +17,8 @@ libcore_to_document := \
dalvik/src/main/java/dalvik/annotation \
dalvik/src/main/java/dalvik/bytecode \
json/src/main/java \
libdvm/src/main/java/dalvik \
libdvm/src/main/java/java \
libart/src/main/java/dalvik \
libart/src/main/java/java \
luni/src/main/java/android \
luni/src/main/java/java \
luni/src/main/java/javax \
......
......@@ -62,7 +62,6 @@ ifneq ($(EMMA_INSTRUMENT_STATIC),true)
endif
endif
libdvm_core_src_files += $(common_core_src_files) $(call all-main-java-files-under,libdvm)
libart_core_src_files += $(common_core_src_files) $(call all-main-java-files-under,libart)
local_javac_flags=-encoding UTF-8
......@@ -75,18 +74,6 @@ local_javac_flags+=-Xmaxwarns 9999999
# Definitions to make the core library.
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(libdvm_core_src_files)
LOCAL_JAVA_RESOURCE_DIRS := $(core_resource_dirs)
LOCAL_NO_STANDARD_LIBRARIES := true
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE := core
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
LOCAL_REQUIRED_MODULES := tzdata
include $(BUILD_JAVA_LIBRARY)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(libart_core_src_files)
LOCAL_JAVA_RESOURCE_DIRS := $(core_resource_dirs)
......@@ -108,7 +95,7 @@ include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(test_src_files)
LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
LOCAL_NO_STANDARD_LIBRARIES := true
LOCAL_JAVA_LIBRARIES := bouncycastle core core-junit okhttp
LOCAL_JAVA_LIBRARIES := core-libart okhttp core-junit bouncycastle
LOCAL_STATIC_JAVA_LIBRARIES := core-tests-support sqlite-jdbc mockwebserver nist-pkix-tests
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_MODULE := core-tests
......@@ -122,7 +109,7 @@ include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(call all-test-java-files-under,support)
LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
LOCAL_NO_STANDARD_LIBRARIES := true
LOCAL_JAVA_LIBRARIES := bouncycastle core core-junit
LOCAL_JAVA_LIBRARIES := core-libart core-junit bouncycastle
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_MODULE := core-tests-support
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
......@@ -135,7 +122,7 @@ include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(call all-test-java-files-under, jsr166-tests)
LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
LOCAL_NO_STANDARD_LIBRARIES := true
LOCAL_JAVA_LIBRARIES := core core-junit
LOCAL_JAVA_LIBRARIES := core-libart core-junit
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_MODULE := jsr166-tests
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
......@@ -168,18 +155,6 @@ LOCAL_MODULE := dex-host
include $(BUILD_HOST_JAVA_LIBRARY)
# Definitions to make the core library.
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(libdvm_core_src_files)
LOCAL_JAVA_RESOURCE_DIRS := $(core_resource_dirs)
LOCAL_NO_STANDARD_LIBRARIES := true
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE := core-hostdex
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
LOCAL_REQUIRED_MODULES := tzdata-host
include $(BUILD_HOST_DALVIK_JAVA_LIBRARY)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(libart_core_src_files)
LOCAL_JAVA_RESOURCE_DIRS := $(core_resource_dirs)
......@@ -200,7 +175,8 @@ ifeq ($(LIBCORE_SKIP_TESTS),)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(test_src_files)
LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
LOCAL_JAVA_LIBRARIES := bouncycastle-hostdex core-junit-hostdex core-tests-support-hostdex okhttp-hostdex
LOCAL_NO_STANDARD_LIBRARIES := true
LOCAL_JAVA_LIBRARIES := core-libart-hostdex okhttp-hostdex bouncycastle-hostdex core-junit-hostdex core-tests-support-hostdex
LOCAL_STATIC_JAVA_LIBRARIES := sqlite-jdbc-host mockwebserver-host nist-pkix-tests-host
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_MODULE_TAGS := optional
......@@ -214,7 +190,8 @@ ifeq ($(LIBCORE_SKIP_TESTS),)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(call all-test-java-files-under,support)
LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
LOCAL_JAVA_LIBRARIES := bouncycastle-hostdex core-junit-hostdex
LOCAL_NO_STANDARD_LIBRARIES := true
LOCAL_JAVA_LIBRARIES := core-libart-hostdex core-junit-hostdex bouncycastle-hostdex
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE := core-tests-support-hostdex
......
# -*- mode: makefile -*-
# Copyright (C) 2013 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
LOCAL_PATH:= $(call my-dir)
##################################################
include $(CLEAR_VARS)
ifeq ($(LIBCORE_SKIP_TESTS),)
# Only compile source java files in this apk.
LOCAL_SRC_FILES := $(call all-java-files-under, src)
##################################################
include $(CLEAR_VARS)
LOCAL_MODULE := benchmarks
LOCAL_STATIC_JAVA_LIBRARIES := \
caliper-prebuilt \
core-tests
LOCAL_JAVA_LIBRARIES := \
bouncycastle \
conscrypt \
core
LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_STATIC_JAVA_LIBRARIES := caliper-prebuilt core-tests
LOCAL_NO_STANDARD_LIBRARIES := true
LOCAL_JAVA_LIBRARIES := core-libart conscrypt core-junit bouncycastle framework
LOCAL_MODULE_TAGS := tests
LOCAL_MODULE_PATH := $(PRODUCT_OUT)/data/caliperperf
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
include $(BUILD_JAVA_LIBRARY)
##################################################
# Prebuilt Java libraries
include $(CLEAR_VARS)
LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := \
caliper-prebuilt:libs/caliper.jar
LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := caliper-prebuilt:libs/caliper.jar
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
include $(BUILD_MULTI_PREBUILT)
endif
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dalvik.system;
import java.util.HashMap;
import java.util.Map;
/**
* 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.
*
* @hide
*/
public final class VMRuntime {
/**
* Holds the VMRuntime singleton.
*/
private static final VMRuntime THE_ONE = new VMRuntime();
private static final Map<String, String> ABI_TO_INSTRUCTION_SET_MAP
= new HashMap<String, String>();
static {
ABI_TO_INSTRUCTION_SET_MAP.put("armeabi", "arm");
ABI_TO_INSTRUCTION_SET_MAP.put("armeabi-v7a", "arm");
ABI_TO_INSTRUCTION_SET_MAP.put("mips", "mips");
ABI_TO_INSTRUCTION_SET_MAP.put("x86", "x86");
}
private int targetSdkVersion;
/**
* Prevents this class from being instantiated.
*/
private VMRuntime() {
}
/**
* Returns the object that represents the VM instance's Dalvik-specific
* runtime environment.
*
* @return the runtime object
*/
public static VMRuntime getRuntime() {
return THE_ONE;
}
/**
* Returns a copy of the VM's command-line property settings.
* These are in the form "name=value" rather than "-Dname=value".
*/
public native String[] properties();
/**
* Returns the VM's boot class path.
*/
public native String bootClassPath();
/**
* Returns the VM's class path.
*/
public native String classPath();
/**
* Returns the VM's version.
*/
public native String vmVersion();
/**
* Returns the name of the shared library providing the VM implementation.
*/
public native String vmLibrary();
/**
* Returns the VM's instruction set.
*/
public String vmInstructionSet() {
return "";
}
/**
* Returns whether the VM is running in 64-bit mode.
*/
public boolean is64Bit() {
return false;
}
/**
* Returns whether the VM is running with JNI checking enabled.
*/
public native boolean isCheckJniEnabled();
/**
* 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.
*
* @return the current ideal heap utilization
*/
public native float getTargetHeapUtilization();
/**
* 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.
*
* <p>This is only a hint to the garbage collector and may be ignored.
*
* @param newTarget the new suggested ideal heap utilization.
* This value may be adjusted internally.
* @return the previous ideal heap utilization
* @throws IllegalArgumentException if newTarget is &lt;= 0.0 or &gt;= 1.0
*/
public float setTargetHeapUtilization(float newTarget) {
if (newTarget <= 0.0f || newTarget >= 1.0f) {
throw new IllegalArgumentException(newTarget +
" out of range (0,1)");
}
/* Synchronize to make sure that only one thread gets
* a given "old" value if both update at the same time.
* Allows for reliable save-and-restore semantics.
*/
synchronized (this) {
float oldTarget = getTargetHeapUtilization();
nativeSetTargetHeapUtilization(newTarget);
return oldTarget;
}
}
/**
* Sets the target SDK version. Should only be called before the
* app starts to run, because it may change the VM's behavior in
* dangerous ways. Use 0 to mean "current" (since callers won't
* necessarily know the actual current SDK version, and the
* allocated version numbers start at 1), and 10000 to mean
* CUR_DEVELOPMENT.
*/
public synchronized void setTargetSdkVersion(int targetSdkVersion) {
this.targetSdkVersion = targetSdkVersion;
setTargetSdkVersionNative(this.targetSdkVersion);
}
/**
* Gets the target SDK version. See {@link #setTargetSdkVersion} for
* special values.
*/
public synchronized int getTargetSdkVersion() {
return targetSdkVersion;
}
private native void setTargetSdkVersionNative(int targetSdkVersion);
/**
* This method exists for binary compatibility. It was part of a
* heap sizing API which was removed in Android 3.0 (Honeycomb).
*/
@Deprecated
public long getMinimumHeapSize() {
return 0;
}
/**
* This method exists for binary compatibility. It was part of a
* heap sizing API which was removed in Android 3.0 (Honeycomb).
*/
@Deprecated
public long setMinimumHeapSize(long size) {
return 0;
}
/**
* This method exists for binary compatibility. It used to
* perform a garbage collection that cleared SoftReferences.
*/
@Deprecated
public void gcSoftReferences() {}
/**
* This method exists for binary compatibility. It is equivalent
* to {@link System#runFinalization}.
*/
@Deprecated
public void runFinalizationSync() {
System.runFinalization();
}
/**
* Implements setTargetHeapUtilization().
*
* @param newTarget the new suggested ideal heap utilization.
* This value may be adjusted internally.
*/
private native void nativeSetTargetHeapUtilization(float newTarget);
/**
* This method exists for binary compatibility. It was part of
* the external allocation API which was removed in Android 3.0 (Honeycomb).
*/
@Deprecated
public boolean trackExternalAllocation(long size) {
return true;
}
/**
* This method exists for binary compatibility. It was part of
* the external allocation API which was removed in Android 3.0 (Honeycomb).
*/
@Deprecated
public void trackExternalFree(long size) {}
/**
* This method exists for binary compatibility. It was part of
* the external allocation API which was removed in Android 3.0 (Honeycomb).
*/
@Deprecated
public long getExternalBytesAllocated() {
return 0;
}
/**
* Tells the VM to enable the JIT compiler. If the VM does not have a JIT
* implementation, calling this method should have no effect.
*/
public native void startJitCompilation();
/**
* Tells the VM to disable the JIT compiler. If the VM does not have a JIT
* implementation, calling this method should have no effect.
*/
public native void disableJitCompilation();
/**
* Returns an array allocated in an area of the Java heap where it will never be moved.
* This is used to implement native allocations on the Java heap, such as DirectByteBuffers
* and Bitmaps.
*/
public native Object newNonMovableArray(Class<?> componentType, int length);
/**
* Returns an array of at least minLength, but potentially larger. The increased size comes from
* avoiding any padding after the array. The amount of padding varies depending on the
* componentType and the memory allocator implementation.
*/
public Object newUnpaddedArray(Class<?> componentType, int minLength) {
// Dalvik has 32bit pointers, the array header is 16bytes plus 4bytes for dlmalloc,
// allocations are 8byte aligned so having 4bytes of array data avoids padding.
if (!componentType.isPrimitive()) {
int size = ((minLength & 1) == 0) ? minLength + 1 : minLength;
return java.lang.reflect.Array.newInstance(componentType, size);
} else if (componentType == char.class) {
int bytes = 20 + (2 * minLength);
int alignedUpBytes = (bytes + 7) & -8;
int dataBytes = alignedUpBytes - 20;
int size = dataBytes / 2;
return new char[size];
} else if (componentType == int.class) {
int size = ((minLength & 1) == 0) ? minLength + 1 : minLength;
return new int[size];
} else if (componentType == byte.class) {
int bytes = 20 + minLength;
int alignedUpBytes = (bytes + 7) & -8;
int dataBytes = alignedUpBytes - 20;
int size = dataBytes;
return new byte[size];
} else if (componentType == boolean.class) {
int bytes = 20 + minLength;
int alignedUpBytes = (bytes + 7) & -8;
int dataBytes = alignedUpBytes - 20;
int size = dataBytes;
return new boolean[size];
} else if (componentType == short.class) {
int bytes = 20 + (2 * minLength);
int alignedUpBytes = (bytes + 7) & -8;
int dataBytes = alignedUpBytes - 20;
int size = dataBytes / 2;
return new short[size];
} else if (componentType == float.class) {
int size = ((minLength & 1) == 0) ? minLength + 1 : minLength;
return new float[size];
} else if (componentType == long.class) {
return new long[minLength];
} else if (componentType == double.class) {
return new double[minLength];
} else {
assert componentType == void.class;
throw new IllegalArgumentException("Can't allocate an array of void");
}
}
/**
* Returns the address of array[0]. This differs from using JNI in that JNI might lie and
* give you the address of a copy of the array when in forcecopy mode.
*/
public native long addressOf(Object array);
/**
* Removes any growth limits, allowing the application to allocate
* up to the maximum heap size.
*/
public native void clearGrowthLimit();
/**
* Returns true if either a Java debugger or native debugger is active.
*/
public native boolean isDebuggerActive();
/**
* Registers a native allocation so that the heap knows about it and performs GC as required.
* If the number of native allocated bytes exceeds the native allocation watermark, the
* function requests a concurrent GC. If the native bytes allocated exceeds a second higher
* watermark, it is determined that the application is registering native allocations at an
* unusually high rate and a GC is performed inside of the function to prevent memory usage
* from excessively increasing.
*/
public native void registerNativeAllocation(int bytes);
/**
* Registers a native free by reducing the number of native bytes accounted for.
*/
public native void registerNativeFree(int bytes);
/**
* Let the heap know of the new process state. This can change allocation and garbage collection
* behavior regarding trimming and compaction.
*/
public native void updateProcessState(int state);
/**
* Fill in dex caches with classes, fields, and methods that are
* already loaded. Typically used after Zygote preloading.
*/
public native void preloadDexCaches();
/**
* Register application info
*/
public static void registerAppInfo(String appDir, String processName, String pkgname) {
// Nothing to do in dalvik.
}
/**
* Returns the runtime instruction set corresponding to a given ABI. Multiple
* compatible ABIs might map to the same instruction set. For example
* {@code armeabi-v7a} and {@code armeabi} might map to the instruction set {@code arm}.
*
* This influences the compilation of the applications classes.
*/
public static String getInstructionSet(String abi) {
final String instructionSet = ABI_TO_INSTRUCTION_SET_MAP.get(abi);
if (instructionSet == null) {
throw new IllegalArgumentException("Unsupported ABI: " + abi);
}
return instructionSet;
}
}
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dalvik.system;
/**
* Provides a limited interface to the Dalvik VM stack. This class is mostly
* used for implementing security checks.
*
* @hide
*/
public final class VMStack {
/**
* Returns the defining class loader of the caller's caller.
*
* @return the requested class loader, or {@code null} if this is the
* bootstrap class loader.
*/
native public static ClassLoader getCallingClassLoader();
/**
* Returns the class of the caller's caller's caller.
*
* @return the requested class, or {@code null}.
*/
native public static Class<?> getStackClass2();
/**
* Creates an array of classes from the methods at the top of the stack.
* We continue until we reach the bottom of the stack or exceed the
* specified maximum depth.
* <p>
* The topmost stack frame (this method) and the one above that (the
* caller) are excluded from the array. Frames with java.lang.reflect
* classes are skipped over.
* <p>
* The classes in the array are the defining classes of the methods.
* <p>
* This is similar to Harmony's VMStack.getClasses, except that this
* implementation doesn't have a concept of "privileged" frames.
*
* @param maxDepth
* maximum number of classes to return, or -1 for all
* @return an array with classes for the most-recent methods on the stack
*/
native public static Class<?>[] getClasses(int maxDepth);
/**
* Returns the first ClassLoader on the call stack that isn't either of
* the passed-in ClassLoaders.
*/
public static ClassLoader getClosestUserClassLoader(ClassLoader bootstrap,
ClassLoader system) {
Class<?>[] stackClasses = VMStack.getClasses(-1);
for (Class<?> stackClass : stackClasses) {
ClassLoader loader = stackClass.getClassLoader();
if (loader != null && loader != bootstrap && loader != system) {
return loader;
}
}
return null;
}
/**
* Retrieves the stack trace from the specified thread.
*
* @param t
* thread of interest
* @return an array of stack trace elements, or null if the thread
* doesn't have a stack trace (e.g. because it exited)
*/
native public static StackTraceElement[] getThreadStackTrace(Thread t);
/**
* Retrieves a partial stack trace from the specified thread into
* the provided array.
*
* @param t
* thread of interest
* @param stackTraceElements
* preallocated array for use when only the top of stack is
* desired. Unused elements will be filled with null values.
* @return the number of elements filled
*/
native public static int fillStackTraceElements(Thread t,
StackTraceElement[] stackTraceElements);
}
This diff is collapsed.
This diff is collapsed.
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.lang;
import dalvik.system.VMRuntime;
import java.lang.ref.FinalizerReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.TimeoutException;
import libcore.util.EmptyArray;
/**
* Calls Object.finalize() on objects in the finalizer reference queue. The VM
* will abort if any finalize() call takes more than the maximum finalize time
* to complete.
*
* @hide
*/
public final class Daemons {
private static final int NANOS_PER_MILLI = 1000 * 1000;
private static final int NANOS_PER_SECOND = NANOS_PER_MILLI * 1000;
private static final long MAX_FINALIZE_NANOS = 10L * NANOS_PER_SECOND;
public static void start() {
ReferenceQueueDaemon.INSTANCE.start();
FinalizerDaemon.INSTANCE.start();
FinalizerWatchdogDaemon.INSTANCE.start();
}
public static void stop() {
ReferenceQueueDaemon.INSTANCE.stop();
FinalizerDaemon.INSTANCE.stop();
FinalizerWatchdogDaemon.INSTANCE.stop();
}
/**
* A background task that provides runtime support to the application.
* Daemons can be stopped and started, but only so that the zygote can be a
* single-threaded process when it forks.
*/
private static abstract class Daemon implements Runnable {
private Thread thread;
public synchronized void start() {
if (thread != null) {
throw new IllegalStateException("already running");
}
thread = new Thread(ThreadGroup.mSystem, this,
getClass().getSimpleName());
thread.setDaemon(true);
thread.start();
}
public abstract void run();
/**
* Returns true while the current thread should continue to run; false
* when it should return.
*/
protected synchronized boolean isRunning() {
return thread != null;
}
public synchronized void interrupt() {
if (thread == null) {
throw new IllegalStateException("not running");
}
thread.interrupt();
}
/**
* Waits for the runtime thread to stop. This interrupts the thread
* currently running the runnable and then waits for it to exit.
*/
public void stop() {
Thread threadToStop;
synchronized (this) {
threadToStop = thread;
thread = null;
}
if (threadToStop == null) {
throw new IllegalStateException("not running");
}
threadToStop.interrupt();
while (true) {
try {
threadToStop.join();
return;
} catch (InterruptedException ignored) {
}
}
}
/**
* Returns the current stack trace of the thread, or an empty stack trace
* if the thread is not currently running.
*/
public synchronized StackTraceElement[] getStackTrace() {
return thread != null ? thread.getStackTrace() : EmptyArray.STACK_TRACE_ELEMENT;
}
}
/**
* This heap management thread moves elements from the garbage collector's
* pending list to the managed reference queue.
*/
private static class ReferenceQueueDaemon extends Daemon {
private static final ReferenceQueueDaemon INSTANCE = new ReferenceQueueDaemon();
@Override public void run() {
while (isRunning()) {
Reference<?> list;
try {
synchronized (ReferenceQueue.class) {
while (ReferenceQueue.unenqueued == null) {
ReferenceQueue.class.wait();
}
list = ReferenceQueue.unenqueued;
ReferenceQueue.unenqueued = null;
}
} catch (InterruptedException e) {
continue;
}
enqueue(list);
}
}
private void enqueue(Reference<?> list) {
while (list != null) {
Reference<?> reference;
// pendingNext is owned by the GC so no synchronization is required
if (list == list.pendingNext) {
reference = list;
reference.pendingNext = null;
list = null;
} else {
reference = list.pendingNext;
list.pendingNext = reference.pendingNext;
reference.pendingNext = null;
}
reference.enqueueInternal();
}
}
}
private static class FinalizerDaemon extends Daemon {
private static final FinalizerDaemon INSTANCE = new FinalizerDaemon();
private final ReferenceQueue<Object> queue = FinalizerReference.queue;
private volatile Object finalizingObject;
private volatile long finalizingStartedNanos;
@Override public void run() {
while (isRunning()) {
// Take a reference, blocking until one is ready or the thread should stop
try {
doFinalize((FinalizerReference<?>) queue.remove());
} catch (InterruptedException ignored) {
}
}
}
@FindBugsSuppressWarnings("FI_EXPLICIT_INVOCATION")
private void doFinalize(FinalizerReference<?> reference) {
FinalizerReference.remove(reference);
Object object = reference.get();
reference.clear();
try {
finalizingStartedNanos = System.nanoTime();
finalizingObject = object;
synchronized (FinalizerWatchdogDaemon.INSTANCE) {
FinalizerWatchdogDaemon.INSTANCE.notify();
}
object.finalize();
} catch (Throwable ex) {
// The RI silently swallows these, but Android has always logged.
System.logE("Uncaught exception thrown by finalizer", ex);
} finally {
finalizingObject = null;
}
}
}
/**
* The watchdog exits the VM if the finalizer ever gets stuck. We consider
* the finalizer to be stuck if it spends more than MAX_FINALIZATION_MILLIS
* on one instance.
*/
private static class FinalizerWatchdogDaemon extends Daemon {
private static final FinalizerWatchdogDaemon INSTANCE = new FinalizerWatchdogDaemon();
@Override public void run() {
while (isRunning()) {
Object object = waitForObject();
if (object == null) {
// We have been interrupted, need to see if this daemon has been stopped.
continue;
}
boolean finalized = waitForFinalization(object);
if (!finalized && !VMRuntime.getRuntime().isDebuggerActive()) {
finalizerTimedOut(object);
break;
}
}
}
private Object waitForObject() {
while (true) {
Object object = FinalizerDaemon.INSTANCE.finalizingObject;
if (object != null) {
return object;
}
synchronized (this) {
// wait until something is ready to be finalized
// http://code.google.com/p/android/issues/detail?id=22778
try {
wait();
} catch (InterruptedException e) {
// Daemon.stop may have interrupted us.
return null;
}
}
}
}
private void sleepFor(long startNanos, long durationNanos) {
while (true) {
long elapsedNanos = System.nanoTime() - startNanos;
long sleepNanos = durationNanos - elapsedNanos;
long sleepMills = sleepNanos / NANOS_PER_MILLI;
if (sleepMills <= 0) {
return;
}
try {
Thread.sleep(sleepMills);
} catch (InterruptedException e) {
if (!isRunning()) {
return;
}
}
}
}
private boolean waitForFinalization(Object object) {
sleepFor(FinalizerDaemon.INSTANCE.finalizingStartedNanos, MAX_FINALIZE_NANOS);
return object != FinalizerDaemon.INSTANCE.finalizingObject;
}
private static void finalizerTimedOut(Object object) {
// The current object has exceeded the finalization deadline; abort!
String message = object.getClass().getName() + ".finalize() timed out after "
+ (MAX_FINALIZE_NANOS / NANOS_PER_SECOND) + " seconds";
Exception syntheticException = new TimeoutException(message);
// We use the stack from where finalize() was running to show where it was stuck.
syntheticException.setStackTrace(FinalizerDaemon.INSTANCE.getStackTrace());
Thread.UncaughtExceptionHandler h = Thread.getDefaultUncaughtExceptionHandler();
if (h == null) {
// If we have no handler, log and exit.
System.logE(message, syntheticException);
System.exit(2);
}
// Otherwise call the handler to do crash reporting.
// We don't just throw because we're not the thread that
// timed out; we're the thread that detected it.
h.uncaughtException(Thread.currentThread(), syntheticException);
}
}
}
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.lang;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import libcore.util.BasicLruCache;
import libcore.util.EmptyArray;
/**
* The superclass of all enumerated types. Actual enumeration types inherit from
* this class, but extending this class does not make a class an enumeration
* type, since the compiler needs to generate special information for it.
*/
public abstract class Enum<E extends Enum<E>> implements Serializable, Comparable<E> {
private static final long serialVersionUID = -4300926546619394005L;
private static final BasicLruCache<Class<? extends Enum>, Object[]> sharedConstantsCache
= new BasicLruCache<Class<? extends Enum>, Object[]>(64) {
@Override protected Object[] create(Class<? extends Enum> enumType) {
if (!enumType.isEnum()) {
return null;
}
Method method = (Method) Class.getDeclaredConstructorOrMethod(
enumType, "values", EmptyArray.CLASS);
try {
return (Object[]) method.invoke((Object[]) null);
} catch (IllegalAccessException impossible) {
throw new AssertionError();
} catch (InvocationTargetException impossible) {
throw new AssertionError();
}
}
};
private final String name;
private final int ordinal;
/**
* Constructor for constants of enum subtypes.
*
* @param name
* the enum constant's declared name.
* @param ordinal
* the enum constant's ordinal, which corresponds to its position
* in the enum declaration, starting at zero.
*/
protected Enum(String name, int ordinal) {
this.name = name;
this.ordinal = ordinal;
}
/**
* Returns the name of this enum constant. The name is the field as it
* appears in the {@code enum} declaration.
*
* @return the name of this enum constant.
* @see #toString()
*/
public final String name() {
return name;
}
/**
* Returns the position of the enum constant in the declaration. The first
* constant has an ordinal value of zero.
*
* @return the ordinal value of this enum constant.
*/
public final int ordinal() {
return ordinal;
}
/**
* Returns a string containing a concise, human-readable description of this
* object. In this case, the enum constant's name is returned.
*
* @return a printable representation of this object.
*/
@Override
public String toString() {
return name;
}
/**
* Compares this object with the specified object and indicates if they are
* equal. In order to be equal, {@code object} must be identical to this
* enum constant.
*
* @param other
* the object to compare this enum constant with.
* @return {@code true} if the specified object is equal to this
* {@code Enum}; {@code false} otherwise.
*/
@Override
public final boolean equals(Object other) {
return this == other;
}
@Override
public final int hashCode() {
return ordinal + (name == null ? 0 : name.hashCode());
}
/**
* {@code Enum} objects are singletons, they may not be cloned. This method
* always throws a {@code CloneNotSupportedException}.
*
* @return does not return.
* @throws CloneNotSupportedException
* is always thrown.
*/
@Override
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Enums may not be cloned");
}
/**
* Compares this object to the specified enum object to determine their
* relative order. This method compares the object's ordinal values, that
* is, their position in the enum declaration.
*
* @param o
* the enum object to compare this object to.
* @return a negative value if the ordinal value of this enum constant is
* less than the ordinal value of {@code o}; 0 if the ordinal
* values of this enum constant and {@code o} are equal; a positive
* value if the ordinal value of this enum constant is greater than
* the ordinal value of {@code o}.
* @see java.lang.Comparable
*/
public final int compareTo(E o) {
return ordinal - o.ordinal();
}
/**
* Returns the enum constant's declaring class.
*
* @return the class object representing the constant's enum type.
*/
@SuppressWarnings("unchecked")
public final Class<E> getDeclaringClass() {
Class<?> myClass = getClass();
Class<?> mySuperClass = myClass.getSuperclass();
if (Enum.class == mySuperClass) {
return (Class<E>)myClass;
}
return (Class<E>)mySuperClass;
}
/**
* Returns the constant with the specified name of the specified enum type.
*
* @param enumType
* the class of the enumerated type to search for the constant
* value.
* @param name
* the name of the constant value to find.
* @return the enum constant.
* @throws NullPointerException
* if either {@code enumType} or {@code name} are {@code null}.
* @throws IllegalArgumentException
* if {@code enumType} is not an enumerated type or does not
* have a constant value called {@code name}.
*/
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) {
if (enumType == null) {
throw new NullPointerException("enumType == null");
} else if (name == null) {
throw new NullPointerException("name == null");
}
T[] values = getSharedConstants(enumType);
if (values == null) {
throw new IllegalArgumentException(enumType + " is not an enum type");
}
for (T value : values) {
if (name.equals(value.name())) {
return value;
}
}
throw new IllegalArgumentException(name + " is not a constant in " + enumType.getName());
}
/**
* Returns a shared, mutable array containing the constants of this enum. It
* is an error to modify the returned array.
*
* @hide
*/
@SuppressWarnings("unchecked") // the cache always returns the type matching enumType
public static <T extends Enum<T>> T[] getSharedConstants(Class<T> enumType) {
return (T[]) sharedConstantsCache.get(enumType);
}
/**
* Enum types may not have finalizers.
*
* @since 1.6
*/
@Override
@SuppressWarnings("FinalizeDoesntCallSuperFinalize")
protected final void finalize() {
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.lang;
/**
* The root class of the Java class hierarchy. All non-primitive types
* (including arrays) inherit either directly or indirectly from this class.
*
* <a name="writing_equals"><h4>Writing a correct {@code equals} method</h4></a>
* <p>Follow this style to write a canonical {@code equals} method:
* <pre>
* // Use @Override to avoid accidental overloading.
* &#x0040;Override public boolean equals(Object o) {
* // Return true if the objects are identical.
* // (This is just an optimization, not required for correctness.)
* if (this == o) {
* return true;
* }
*
* // Return false if the other object has the wrong type.
* // This type may be an interface depending on the interface's specification.
* if (!(o instanceof MyType)) {
* return false;
* }
*
* // Cast to the appropriate type.
* // This will succeed because of the instanceof, and lets us access private fields.
* MyType lhs = (MyType) o;
*
* // Check each field. Primitive fields, reference fields, and nullable reference
* // fields are all treated differently.
* return primitiveField == lhs.primitiveField &amp;&amp;
* referenceField.equals(lhs.referenceField) &amp;&amp;
* (nullableField == null ? lhs.nullableField == null
* : nullableField.equals(lhs.nullableField));
* }
* </pre>
* <p>If you override {@code equals}, you should also override {@code hashCode}: equal
* instances must have equal hash codes.
*
* <p>See <i>Effective Java</i> item 8 for much more detail and clarification.
*
* <a name="writing_hashCode"><h4>Writing a correct {@code hashCode} method</h4></a>
* <p>Follow this style to write a canonical {@code hashCode} method:
* <pre>
* &#x0040;Override public int hashCode() {
* // Start with a non-zero constant.
* int result = 17;
*
* // Include a hash for each field.
* result = 31 * result + (booleanField ? 1 : 0);
*
* result = 31 * result + byteField;
* result = 31 * result + charField;
* result = 31 * result + shortField;
* result = 31 * result + intField;
*
* result = 31 * result + (int) (longField ^ (longField >>> 32));
*
* result = 31 * result + Float.floatToIntBits(floatField);
*
* long doubleFieldBits = Double.doubleToLongBits(doubleField);
* result = 31 * result + (int) (doubleFieldBits ^ (doubleFieldBits >>> 32));
*
* result = 31 * result + Arrays.hashCode(arrayField);
*
* result = 31 * result + referenceField.hashCode();
* result = 31 * result +
* (nullableReferenceField == null ? 0
* : nullableReferenceField.hashCode());
*
* return result;
* }
* </pre>
*
* <p>If you don't intend your type to be used as a hash key, don't simply rely on the default
* {@code hashCode} implementation, because that silently and non-obviously breaks any future
* code that does use your type as a hash key. You should throw instead:
* <pre>
* &#x0040;Override public int hashCode() {
* throw new UnsupportedOperationException();
* }
* </pre>
*
* <p>See <i>Effective Java</i> item 9 for much more detail and clarification.
*
* <a name="writing_toString"><h4>Writing a useful {@code toString} method</h4></a>
* <p>For debugging convenience, it's common to override {@code toString} in this style:
* <pre>
* &#x0040;Override public String toString() {
* return getClass().getName() + "[" +
* "primitiveField=" + primitiveField + ", " +
* "referenceField=" + referenceField + ", " +
* "arrayField=" + Arrays.toString(arrayField) + "]";
* }
* </pre>
* <p>The set of fields to include is generally the same as those that would be tested
* in your {@code equals} implementation.
* <p>See <i>Effective Java</i> item 10 for much more detail and clarification.
*/
public class Object {
/**
* Constructs a new instance of {@code Object}.
*/
public Object() {
}
/**
* Creates and returns a copy of this {@code Object}. The default
* implementation returns a so-called "shallow" copy: It creates a new
* instance of the same class and then copies the field values (including
* object references) from this instance to the new instance. A "deep" copy,
* in contrast, would also recursively clone nested objects. A subclass that
* needs to implement this kind of cloning should call {@code super.clone()}
* to create the new instance and then create deep copies of the nested,
* mutable objects.
*
* @return a copy of this object.
* @throws CloneNotSupportedException
* if this object's class does not implement the {@code
* Cloneable} interface.
*/
protected Object clone() throws CloneNotSupportedException {
if (!(this instanceof Cloneable)) {
throw new CloneNotSupportedException("Class doesn't implement Cloneable");
}
return internalClone((Cloneable) this);
}
/*
* Native helper method for cloning.
*/
private native Object internalClone(Cloneable o);
/**
* Compares this instance with the specified object and indicates if they
* are equal. In order to be equal, {@code o} must represent the same object
* as this instance using a class-specific comparison. The general contract
* is that this comparison should be reflexive, symmetric, and transitive.
* Also, no object reference other than null is equal to null.
*
* <p>The default implementation returns {@code true} only if {@code this ==
* o}. See <a href="{@docRoot}reference/java/lang/Object.html#writing_equals">Writing a correct
* {@code equals} method</a>
* if you intend implementing your own {@code equals} method.
*
* <p>The general contract for the {@code equals} and {@link
* #hashCode()} methods is that if {@code equals} returns {@code true} for
* any two objects, then {@code hashCode()} must return the same value for
* these objects. This means that subclasses of {@code Object} usually
* override either both methods or neither of them.
*
* @param o
* the object to compare this instance with.
* @return {@code true} if the specified object is equal to this {@code
* Object}; {@code false} otherwise.
* @see #hashCode
*/
public boolean equals(Object o) {
return this == o;
}
/**
* Invoked when the garbage collector has detected that this instance is no longer reachable.
* The default implementation does nothing, but this method can be overridden to free resources.
*
* <p>Note that objects that override {@code finalize} are significantly more expensive than
* objects that don't. Finalizers may be run a long time after the object is no longer
* reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup.
* Note also that finalizers are run on a single VM-wide finalizer thread,
* so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary
* for a class that has a native peer and needs to call a native method to destroy that peer.
* Even then, it's better to provide an explicit {@code close} method (and implement
* {@link java.io.Closeable}), and insist that callers manually dispose of instances. This
* works well for something like files, but less well for something like a {@code BigInteger}
* where typical calling code would have to deal with lots of temporaries. Unfortunately,
* code that creates lots of temporaries is the worst kind of code from the point of view of
* the single finalizer thread.
*
* <p>If you <i>must</i> use finalizers, consider at least providing your own
* {@link java.lang.ref.ReferenceQueue} and having your own thread process that queue.
*
* <p>Unlike constructors, finalizers are not automatically chained. You are responsible for
* calling {@code super.finalize()} yourself.
*
* <p>Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer
* thread.
*
* See <i>Effective Java</i> Item 7, "Avoid finalizers" for more.
*/
@FindBugsSuppressWarnings("FI_EMPTY")
protected void finalize() throws Throwable {
}
/**
* Returns the unique instance of {@link Class} that represents this
* object's class. Note that {@code getClass()} is a special case in that it
* actually returns {@code Class<? extends Foo>} where {@code Foo} is the
* erasure of the type of the expression {@code getClass()} was called upon.
* <p>
* As an example, the following code actually compiles, although one might
* think it shouldn't:
* <p>
* <pre>{@code
* List<Integer> l = new ArrayList<Integer>();
* Class<? extends List> c = l.getClass();}</pre>
*
* @return this object's {@code Class} instance.
*/
public final native Class<?> getClass();
/**
* Returns an integer hash code for this object. By contract, any two
* objects for which {@link #equals} returns {@code true} must return
* the same hash code value. This means that subclasses of {@code Object}
* usually override both methods or neither method.
*
* <p>Note that hash values must not change over time unless information used in equals
* comparisons also changes.
*
* <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_hashCode">Writing a correct
* {@code hashCode} method</a>
* if you intend implementing your own {@code hashCode} method.
*
* @return this object's hash code.
* @see #equals
*/
public native int hashCode();
/**
* Causes a thread which is waiting on this object's monitor (by means of
* calling one of the {@code wait()} methods) to be woken up. If more than
* one thread is waiting, one of them is chosen at the discretion of the
* VM. The chosen thread will not run immediately. The thread
* that called {@code notify()} has to release the object's monitor first.
* Also, the chosen thread still has to compete against other threads that
* try to synchronize on the same object.
*
* <p>This method can only be invoked by a thread which owns this object's
* monitor. A thread becomes owner of an object's monitor
* <ul>
* <li>by executing a synchronized method of that object;</li>
* <li>by executing the body of a {@code synchronized} statement that
* synchronizes on the object;</li>
* <li>by executing a synchronized static method if the object is of type
* {@code Class}.</li>
* </ul>
*
* @see #notifyAll
* @see #wait()
* @see #wait(long)
* @see #wait(long,int)
* @see java.lang.Thread
*/
public final native void notify();
/**
* Causes all threads which are waiting on this object's monitor (by means
* of calling one of the {@code wait()} methods) to be woken up. The threads
* will not run immediately. The thread that called {@code notify()} has to
* release the object's monitor first. Also, the threads still have to
* compete against other threads that try to synchronize on the same object.
*
* <p>This method can only be invoked by a thread which owns this object's
* monitor. A thread becomes owner of an object's monitor
* <ul>
* <li>by executing a synchronized method of that object;</li>
* <li>by executing the body of a {@code synchronized} statement that
* synchronizes on the object;</li>
* <li>by executing a synchronized static method if the object is of type
* {@code Class}.</li>
* </ul>
*
* @throws IllegalMonitorStateException
* if the thread calling this method is not the owner of this
* object's monitor.
* @see #notify
* @see #wait()
* @see #wait(long)
* @see #wait(long,int)
* @see java.lang.Thread
*/
public final native void notifyAll();
/**
* Returns a string containing a concise, human-readable description of this
* object. Subclasses are encouraged to override this method and provide an
* implementation that takes into account the object's type and data. The
* default implementation is equivalent to the following expression:
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())</pre>
* <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_toString">Writing a useful
* {@code toString} method</a>
* if you intend implementing your own {@code toString} method.
*
* @return a printable representation of this object.
*/
public String toString() {
return getClass().getName() + '@' + Integer.toHexString(hashCode());
}
/**
* Causes the calling thread to wait until another thread calls the {@code
* notify()} or {@code notifyAll()} method of this object. This method can
* only be invoked by a thread which owns this object's monitor; see
* {@link #notify()} on how a thread can become the owner of a monitor.
*
* <p>A waiting thread can be sent {@code interrupt()} to cause it to
* prematurely stop waiting, so {@code wait} should be called in a loop to
* check that the condition that has been waited for has been met before
* continuing.
*
* <p>While the thread waits, it gives up ownership of this object's
* monitor. When it is notified (or interrupted), it re-acquires the monitor
* before it starts running.
*
* @throws IllegalMonitorStateException
* if the thread calling this method is not the owner of this
* object's monitor.
* @throws InterruptedException if the current thread has been interrupted.
* The interrupted status of the current thread will be cleared before the exception
* is thrown.
* @see #notify
* @see #notifyAll
* @see #wait(long)
* @see #wait(long,int)
* @see java.lang.Thread
*/
public final void wait() throws InterruptedException {
wait(0, 0);
}
/**
* Causes the calling thread to wait until another thread calls the {@code
* notify()} or {@code notifyAll()} method of this object or until the
* specified timeout expires. This method can only be invoked by a thread
* which owns this object's monitor; see {@link #notify()} on how a thread
* can become the owner of a monitor.
*
* <p>A waiting thread can be sent {@code interrupt()} to cause it to
* prematurely stop waiting, so {@code wait} should be called in a loop to
* check that the condition that has been waited for has been met before
* continuing.
*
* <p>While the thread waits, it gives up ownership of this object's
* monitor. When it is notified (or interrupted), it re-acquires the monitor
* before it starts running.
*
* <p>A timeout of zero means the calling thread should wait forever unless interrupted or
* notified.
*
* @param millis
* the maximum time to wait in milliseconds.
* @throws IllegalArgumentException
* if {@code millis < 0}.
* @throws IllegalMonitorStateException
* if the thread calling this method is not the owner of this
* object's monitor.
* @throws InterruptedException if the current thread has been interrupted.
* The interrupted status of the current thread will be cleared before the exception
* is thrown.
* @see #notify
* @see #notifyAll
* @see #wait()
* @see #wait(long,int)
* @see java.lang.Thread
*/
public final void wait(long millis) throws InterruptedException {
wait(millis, 0);
}
/**
* Causes the calling thread to wait until another thread calls the {@code
* notify()} or {@code notifyAll()} method of this object or until the
* specified timeout expires. This method can only be invoked by a thread
* that owns this object's monitor; see {@link #notify()} on how a thread
* can become the owner of a monitor.
*
* <p>A waiting thread can be sent {@code interrupt()} to cause it to
* prematurely stop waiting, so {@code wait} should be called in a loop to
* check that the condition that has been waited for has been met before
* continuing.
*
* <p>While the thread waits, it gives up ownership of this object's
* monitor. When it is notified (or interrupted), it re-acquires the monitor
* before it starts running.
*
* <p>A timeout of zero means the calling thread should wait forever unless interrupted or
* notified.
*
* @param millis
* the maximum time to wait in milliseconds.
* @param nanos
* the fraction of a millisecond to wait, specified in
* nanoseconds.
* @throws IllegalArgumentException
* if {@code millis < 0}, {@code nanos < 0} or {@code nanos >
* 999999}.
* @throws IllegalMonitorStateException
* if the thread calling this method is not the owner of this
* object's monitor.
* @throws InterruptedException if the current thread has been interrupted.
* The interrupted status of the current thread will be cleared before the exception
* is thrown.
* @see #notify
* @see #notifyAll
* @see #wait()
* @see #wait(long,int)
* @see java.lang.Thread
*/
public final native void wait(long millis, int nanos) throws InterruptedException;
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.lang;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
class VMClassLoader {
/**
* Get a resource from a file in the bootstrap class path.
*
* It would be simpler to just walk through the class path elements
* ourselves, but that would require reopening Jar files.
*
* We assume that the bootclasspath can't change once the VM has
* started. This assumption seems to be supported by the spec.
*/
static URL getResource(String name) {
int numEntries = getBootClassPathSize();
for (int i = 0; i < numEntries; i++) {
String urlStr = getBootClassPathResource(name, i);
if (urlStr != null) {
try {
return new URL(urlStr);
} catch (MalformedURLException mue) {
mue.printStackTrace();
// unexpected; keep going
}
}
}
return null;
}
/*
* Get an enumeration with all matching resources.
*/
static List<URL> getResources(String name) {
ArrayList<URL> list = new ArrayList<URL>();
int numEntries = getBootClassPathSize();
for (int i = 0; i < numEntries; i++) {
String urlStr = getBootClassPathResource(name, i);
if (urlStr != null) {
try {
list.add(new URL(urlStr));
} catch (MalformedURLException mue) {
mue.printStackTrace();
// unexpected; keep going
}
}
}
return list;
}
/**
* Load class with bootstrap class loader.
*/
native static Class loadClass(String name, boolean resolve) throws ClassNotFoundException;
native static Class getPrimitiveClass(char type);
native static Class findLoadedClass(ClassLoader cl, String name);
/**
* Boot class path manipulation, for getResources().
*/
native private static int getBootClassPathSize();
native private static String getBootClassPathResource(String name, int index);
}
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.lang;
class VMThread {
Thread thread;
int vmData;
VMThread(Thread t) {
thread = t;
}
native static void create(Thread t, long stackSize);
static native Thread currentThread();
static native boolean interrupted();
static native void sleep (long msec, int nsec) throws InterruptedException;
static native void yield();
native void interrupt();
native boolean isInterrupted();
/**
* Starts the VMThread (and thus the Java Thread) with the given
* stack size.
*/
void start(long stackSize) {
VMThread.create(thread, stackSize);
}
/**
* Queries whether this Thread holds a monitor lock on the
* given object.
*/
native boolean holdsLock(Object object);
native void setPriority(int newPriority);
native int getStatus();
/**
* Holds a mapping from native Thread statuses to Java one. Required for
* translating back the result of getStatus().
*/
static final Thread.State[] STATE_MAP = new Thread.State[] {
Thread.State.TERMINATED, // ZOMBIE
Thread.State.RUNNABLE, // RUNNING
Thread.State.TIMED_WAITING, // TIMED_WAIT
Thread.State.BLOCKED, // MONITOR
Thread.State.WAITING, // WAIT
Thread.State.NEW, // INITIALIZING
Thread.State.NEW, // STARTING
Thread.State.RUNNABLE, // NATIVE
Thread.State.WAITING, // VMWAIT
Thread.State.RUNNABLE // SUSPENDED
};
/**
* Tell the VM that the thread's name has changed. This is useful for
* DDMS, which would otherwise be oblivious to Thread.setName calls.
*/
native void nameChanged(String newName);
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.lang.ref;
/**
* Provides an abstract class which describes behavior common to all reference
* objects. It is not possible to create immediate subclasses of
* {@code Reference} in addition to the ones provided by this package. It is
* also not desirable to do so, since references require very close cooperation
* with the system's garbage collector. The existing, specialized reference
* classes should be used instead.
*
* <p>Three different type of references exist, each being weaker than the preceding one:
* {@link java.lang.ref.SoftReference}, {@link java.lang.ref.WeakReference}, and
* {@link java.lang.ref.PhantomReference}. "Weakness" here means that less restrictions are
* being imposed on the garbage collector as to when it is allowed to
* actually garbage-collect the referenced object.
*
* <p>In order to use reference objects properly it is important to understand
* the different types of reachability that trigger their clearing and
* enqueueing. The following table lists these, from strongest to weakest.
* For each row, an object is said to have the reachability on the left side
* if (and only if) it fulfills all of the requirements on the right side. In
* all rows, consider the <em>root set</em> to be a set of references that
* are "resistant" to garbage collection (that is, running threads, method
* parameters, local variables, static fields and the like).
*
* <p><table>
* <tr>
* <td>Strongly reachable</td>
* <td> <ul>
* <li>There exists at least one path from the root set to the object that does not traverse any
* instance of a {@code java.lang.ref.Reference} subclass.
* </li>
* </ul> </td>
* </tr>
*
* <tr>
* <td>Softly reachable</td>
* <td> <ul>
* <li>The object is not strongly reachable.</li>
* <li>There exists at least one path from the root set to the object that does traverse
* a {@code java.lang.ref.SoftReference} instance, but no {@code java.lang.ref.WeakReference}
* or {@code java.lang.ref.PhantomReference} instances.</li>
* </ul> </td>
* </tr>
*
* <tr>
* <td>Weakly reachable</td>
* <td> <ul>
* <li>The object is neither strongly nor softly reachable.</li>
* <li>There exists at least one path from the root set to the object that does traverse a
* {@code java.lang.ref.WeakReference} instance, but no {@code java.lang.ref.PhantomReference}
* instances.</li>
* </ul> </td>
* </tr>
*
* <tr>
* <td>Phantom-reachable</td>
* <td> <ul>
* <li>The object is neither strongly, softly, nor weakly reachable.</li>
* <li>The object is referenced by a {@code java.lang.ref.PhantomReference} instance.</li>
* <li>The object has already been finalized.</li>
* </ul> </td>
* </tr>
* </table>
*/
public abstract class Reference<T> {
/**
* The object to which this reference refers.
* VM requirement: this field <em>must</em> be called "referent"
* and be an object.
*/
volatile T referent;
/**
* If non-null, the queue on which this reference will be enqueued
* when the referent is appropriately reachable.
* VM requirement: this field <em>must</em> be called "queue"
* and be a java.lang.ref.ReferenceQueue.
*/
volatile ReferenceQueue<? super T> queue;
/**
* Used internally by java.lang.ref.ReferenceQueue.
* VM requirement: this field <em>must</em> be called "queueNext"
* and be a java.lang.ref.Reference.
*/
@SuppressWarnings("unchecked")
volatile Reference queueNext;
/**
* Used internally by the VM. This field forms a circular and
* singly linked list of reference objects discovered by the
* garbage collector and awaiting processing by the reference
* queue thread.
*
* @hide
*/
public volatile Reference<?> pendingNext;
/**
* Constructs a new instance of this class.
*/
Reference() {
}
Reference(T r, ReferenceQueue<? super T> q) {
referent = r;
queue = q;
}
/**
* Makes the referent {@code null}. This does not force the reference
* object to be enqueued.
*/
public void clear() {
referent = null;
}
/**
* Adds an object to its reference queue.
*
* @return {@code true} if this call has caused the {@code Reference} to
* become enqueued, or {@code false} otherwise
*
* @hide
*/
public final synchronized boolean enqueueInternal() {
if (queue != null && queueNext == null) {
queue.enqueue(this);
queue = null;
return true;
}
return false;
}
/**
* Forces the reference object to be enqueued if it has been associated with
* a queue.
*
* @return {@code true} if this call has caused the {@code Reference} to
* become enqueued, or {@code false} otherwise
*/
public boolean enqueue() {
return enqueueInternal();
}
/**
* Returns the referent of the reference object.
*
* @return the referent to which reference refers, or {@code null} if the
* object has been cleared.
*/
public T get() {
return referent;
}
/**
* Checks whether the reference object has been enqueued.
*
* @return {@code true} if the {@code Reference} has been enqueued, {@code
* false} otherwise
*/
public boolean isEnqueued() {
return queueNext != null;
}
}
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment