java_lang_Thread.cc revision 59952167697d3b7e6655cb76d087a809c4f615d8
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "common_throws.h"
18#include "debugger.h"
19#include "jni_internal.h"
20#include "monitor.h"
21#include "mirror/object.h"
22#include "scoped_fast_native_object_access.h"
23#include "scoped_thread_state_change.h"
24#include "ScopedUtfChars.h"
25#include "thread.h"
26#include "thread_list.h"
27#include "verify_object-inl.h"
28
29namespace art {
30
31static jobject Thread_currentThread(JNIEnv* env, jclass) {
32  ScopedFastNativeObjectAccess soa(env);
33  return soa.AddLocalReference<jobject>(soa.Self()->GetPeer());
34}
35
36static jboolean Thread_interrupted(JNIEnv* env, jclass) {
37  return static_cast<JNIEnvExt*>(env)->self->Interrupted() ? JNI_TRUE : JNI_FALSE;
38}
39
40static jboolean Thread_isInterrupted(JNIEnv* env, jobject java_thread) {
41  ScopedFastNativeObjectAccess soa(env);
42  MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
43  Thread* thread = Thread::FromManagedThread(soa, java_thread);
44  return (thread != NULL) ? thread->IsInterrupted() : JNI_FALSE;
45}
46
47static void Thread_nativeCreate(JNIEnv* env, jclass, jobject java_thread, jlong stack_size,
48                                jboolean daemon) {
49  Thread::CreateNativeThread(env, java_thread, stack_size, daemon == JNI_TRUE);
50}
51
52static jint Thread_nativeGetStatus(JNIEnv* env, jobject java_thread, jboolean has_been_started) {
53  // Ordinals from Java's Thread.State.
54  const jint kJavaNew = 0;
55  const jint kJavaRunnable = 1;
56  const jint kJavaBlocked = 2;
57  const jint kJavaWaiting = 3;
58  const jint kJavaTimedWaiting = 4;
59  const jint kJavaTerminated = 5;
60
61  ScopedObjectAccess soa(env);
62  ThreadState internal_thread_state = (has_been_started ? kTerminated : kStarting);
63  MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
64  Thread* thread = Thread::FromManagedThread(soa, java_thread);
65  if (thread != NULL) {
66    internal_thread_state = thread->GetState();
67  }
68  switch (internal_thread_state) {
69    case kTerminated:                     return kJavaTerminated;
70    case kRunnable:                       return kJavaRunnable;
71    case kTimedWaiting:                   return kJavaTimedWaiting;
72    case kSleeping:                       return kJavaTimedWaiting;
73    case kBlocked:                        return kJavaBlocked;
74    case kWaiting:                        return kJavaWaiting;
75    case kStarting:                       return kJavaNew;
76    case kNative:                         return kJavaRunnable;
77    case kWaitingForGcToComplete:         return kJavaWaiting;
78    case kWaitingPerformingGc:            return kJavaWaiting;
79    case kWaitingForCheckPointsToRun:     return kJavaWaiting;
80    case kWaitingForDebuggerSend:         return kJavaWaiting;
81    case kWaitingForDebuggerToAttach:     return kJavaWaiting;
82    case kWaitingInMainDebuggerLoop:      return kJavaWaiting;
83    case kWaitingForDebuggerSuspension:   return kJavaWaiting;
84    case kWaitingForDeoptimization:       return kJavaWaiting;
85    case kWaitingForJniOnLoad:            return kJavaWaiting;
86    case kWaitingForSignalCatcherOutput:  return kJavaWaiting;
87    case kWaitingInMainSignalCatcherLoop: return kJavaWaiting;
88    case kWaitingForMethodTracingStart:   return kJavaWaiting;
89    case kSuspended:                      return kJavaRunnable;
90    // Don't add a 'default' here so the compiler can spot incompatible enum changes.
91  }
92  LOG(ERROR) << "Unexpected thread state: " << internal_thread_state;
93  return -1;  // Unreachable.
94}
95
96static jboolean Thread_nativeHoldsLock(JNIEnv* env, jobject java_thread, jobject java_object) {
97  ScopedObjectAccess soa(env);
98  mirror::Object* object = soa.Decode<mirror::Object*>(java_object);
99  if (object == NULL) {
100    ThrowNullPointerException(NULL, "object == null");
101    return JNI_FALSE;
102  }
103  MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
104  Thread* thread = Thread::FromManagedThread(soa, java_thread);
105  return thread->HoldsLock(object);
106}
107
108static void Thread_nativeInterrupt(JNIEnv* env, jobject java_thread) {
109  ScopedFastNativeObjectAccess soa(env);
110  MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
111  Thread* thread = Thread::FromManagedThread(soa, java_thread);
112  if (thread != NULL) {
113    thread->Interrupt(soa.Self());
114  }
115}
116
117static void Thread_nativeSetName(JNIEnv* env, jobject peer, jstring java_name) {
118  ScopedUtfChars name(env, java_name);
119  Thread* self;
120  {
121    ScopedObjectAccess soa(env);
122    if (soa.Decode<mirror::Object*>(peer) == soa.Self()->GetPeer()) {
123      soa.Self()->SetThreadName(name.c_str());
124      return;
125    }
126    self = soa.Self();
127  }
128  // Suspend thread to avoid it from killing itself while we set its name. We don't just hold the
129  // thread list lock to avoid this, as setting the thread name causes mutator to lock/unlock
130  // in the DDMS send code.
131  bool timed_out;
132  // Take suspend thread lock to avoid races with threads trying to suspend this one.
133  Thread* thread;
134  {
135    MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
136    thread = ThreadList::SuspendThreadByPeer(peer, true, false, &timed_out);
137  }
138  if (thread != NULL) {
139    {
140      ScopedObjectAccess soa(env);
141      thread->SetThreadName(name.c_str());
142    }
143    Runtime::Current()->GetThreadList()->Resume(thread, false);
144  } else if (timed_out) {
145    LOG(ERROR) << "Trying to set thread name to '" << name.c_str() << "' failed as the thread "
146        "failed to suspend within a generous timeout.";
147  }
148}
149
150/*
151 * Alter the priority of the specified thread.  "new_priority" will range
152 * from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY (1-10), with "normal"
153 * threads at Thread.NORM_PRIORITY (5).
154 */
155static void Thread_nativeSetPriority(JNIEnv* env, jobject java_thread, jint new_priority) {
156  ScopedObjectAccess soa(env);
157  MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
158  Thread* thread = Thread::FromManagedThread(soa, java_thread);
159  if (thread != NULL) {
160    thread->SetNativePriority(new_priority);
161  }
162}
163
164static void Thread_sleep(JNIEnv* env, jclass, jobject java_lock, jlong ms, jint ns) {
165  ScopedFastNativeObjectAccess soa(env);
166  mirror::Object* lock = soa.Decode<mirror::Object*>(java_lock);
167  Monitor::Wait(Thread::Current(), lock, ms, ns, true, kSleeping);
168}
169
170/*
171 * Causes the thread to temporarily pause and allow other threads to execute.
172 *
173 * The exact behavior is poorly defined.  Some discussion here:
174 *   http://www.cs.umd.edu/~pugh/java/memoryModel/archive/0944.html
175 */
176static void Thread_yield(JNIEnv*, jobject) {
177  sched_yield();
178}
179
180static JNINativeMethod gMethods[] = {
181  NATIVE_METHOD(Thread, currentThread, "!()Ljava/lang/Thread;"),
182  NATIVE_METHOD(Thread, interrupted, "!()Z"),
183  NATIVE_METHOD(Thread, isInterrupted, "!()Z"),
184  NATIVE_METHOD(Thread, nativeCreate, "(Ljava/lang/Thread;JZ)V"),
185  NATIVE_METHOD(Thread, nativeGetStatus, "(Z)I"),
186  NATIVE_METHOD(Thread, nativeHoldsLock, "(Ljava/lang/Object;)Z"),
187  NATIVE_METHOD(Thread, nativeInterrupt, "!()V"),
188  NATIVE_METHOD(Thread, nativeSetName, "(Ljava/lang/String;)V"),
189  NATIVE_METHOD(Thread, nativeSetPriority, "(I)V"),
190  NATIVE_METHOD(Thread, sleep, "!(Ljava/lang/Object;JI)V"),
191  NATIVE_METHOD(Thread, yield, "()V"),
192};
193
194void register_java_lang_Thread(JNIEnv* env) {
195  REGISTER_NATIVE_METHODS("java/lang/Thread");
196}
197
198}  // namespace art
199