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