Fix races in thread list Unregister.

First race:
We were releasing the thin_lock_id in Unregister before the thread
was not suspended. This could cause problems in
SuspendThreadByThreadId since there was a small window of time where
two threads could share the same thread id. This race caused an
occasional check failure in SuspendThreadByThreadId.

Second race:
We were setting the thin_lock_thread_id_ to 0 in Unregister before
waiting to not be suspended. This caused another race in
SuspendThreadByThreadId where we modified the thread suspend count,
busy waited, but didn't find the thread the next iteration. This
meant that we were returning null even though we had modified the
suspend count. This caused the suspend count to not get decremented
since the caller didn't know that the suspend count had been
increased. Removing the self->thin_lock_thread_id_ = 0 in
ThreadList::UnRegister fixes this race.

Added a bit of additional checks and logging to prevent these issues
from resurfacing, other misc cleanup.

Added thread names to threads in ThreadStress.

Bug: 11319866

Change-Id: I48e3a0700193b72079e450be1e924a2f88cf52e2
diff --git a/runtime/thread.cc b/runtime/thread.cc
index d816ca1..297fa45 100644
--- a/runtime/thread.cc
+++ b/runtime/thread.cc
@@ -586,11 +586,11 @@
   if ((old_state_and_flags.as_struct.flags & kCheckpointRequest) != 0) {
     return false;  // Fail, already a checkpoint pending.
   }
-  CHECK(checkpoint_function_ == NULL);
+  CHECK(checkpoint_function_ == nullptr);
   checkpoint_function_ = function;
   // Checkpoint function installed now install flag bit.
   // We must be runnable to request a checkpoint.
-  old_state_and_flags.as_struct.state = kRunnable;
+  DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
   union StateAndFlags new_state_and_flags = old_state_and_flags;
   new_state_and_flags.as_struct.flags |= kCheckpointRequest;
   int succeeded = android_atomic_cmpxchg(old_state_and_flags.as_int, new_state_and_flags.as_int,
@@ -2120,12 +2120,11 @@
     opeer_ = visitor(opeer_, arg);
   }
   if (exception_ != nullptr) {
-    exception_ = reinterpret_cast<mirror::Throwable*>(visitor(exception_, arg));
+    exception_ = down_cast<mirror::Throwable*>(visitor(exception_, arg));
   }
   throw_location_.VisitRoots(visitor, arg);
   if (class_loader_override_ != nullptr) {
-    class_loader_override_ = reinterpret_cast<mirror::ClassLoader*>(
-        visitor(class_loader_override_, arg));
+    class_loader_override_ = down_cast<mirror::ClassLoader*>(visitor(class_loader_override_, arg));
   }
   jni_env_->locals.VisitRoots(visitor, arg);
   jni_env_->monitors.VisitRoots(visitor, arg);
@@ -2144,7 +2143,7 @@
       frame.this_object_ = visitor(frame.this_object_, arg);
     }
     DCHECK(frame.method_ != nullptr);
-    frame.method_ = reinterpret_cast<mirror::ArtMethod*>(visitor(frame.method_, arg));
+    frame.method_ = down_cast<mirror::ArtMethod*>(visitor(frame.method_, arg));
   }
 }