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