Found 655261 results in 91295 files, showing top 150 files (show more).
github.com/html5rocks/www.html5rocks.com:static/demos/lemdoodle/examples/lem-planes/combined.js: [ master, ]
5051:   'needle': ['intro-finale/items-needle-thread', 'intro-finale/items-needle'],
5086:   'thread': ['intro-finale/items-thread', 'intro-finale/items-thread'],
5084:   'thread-thimble': ['intro-finale/items-thread-thimble',
5085:                      'intro-finale/items-thread-thimble'],
5102:     'needle', 'halo', 'noodles', 'neutron', 'nose'
5105:     'thread', 'pinstripe', 'neutron', 'noodles', 'clove'
5125:     'thread', 'thimble', 'earmuffs', 'neutron', 'nose'
5131:     'thread', 'thimble', 'noodles', 'neutron', 'nose', 'gnocchi', 'rivet',
13797:     'intro-finale/items-needle-thread',
13798:     'intro-finale/items-needle',
13839:     'intro-finale/items-thread-thimble',
13840:     'intro-finale/items-thread',
15100:   'intro-finale/items-needle-thread': { width: 68, height: 65, x: 834, y: 0 },
15101:   'intro-finale/items-needle': { top: 8, width: 59, height: 51, x: 904, y: 0 },
15142:   'intro-finale/items-thread-thimble': { left: 2, top: 11, bottom: 14, right: 11, width: 52, height: 40, x: 690, y: 96 },
15143:   'intro-finale/items-thread': { left: 4, top: 16, bottom: 15, right: 13, width: 48, height: 34, x: 744, y: 96 },
github.com/html5rocks/www.html5rocks.com:static/demos/lemdoodle/examples/lem-embedded/combined.js: [ master, ]
5024:   'needle': ['intro-finale/items-needle-thread', 'intro-finale/items-needle'],
5059:   'thread': ['intro-finale/items-thread', 'intro-finale/items-thread'],
5057:   'thread-thimble': ['intro-finale/items-thread-thimble',
5058:                      'intro-finale/items-thread-thimble'],
5075:     'needle', 'halo', 'noodles', 'neutron', 'nose'
5078:     'thread', 'pinstripe', 'neutron', 'noodles', 'clove'
5098:     'thread', 'thimble', 'earmuffs', 'neutron', 'nose'
5104:     'thread', 'thimble', 'noodles', 'neutron', 'nose', 'gnocchi', 'rivet',
13827:               // First run: Thread + thimble
13828:               nItems = ['thread', 'thimble'];
13831:               // Second run: Thread/thimble + random item that’s neither
13832:               nItems[0] = 'thread-thimble';
13836:               } while ((nItems[1] == 'thread-thimble') ||
13837:                        (nItems[1] == 'thread') || (nItems[1] == 'thimble'));
13843:             nItems = ['needle', 'noodles'];
13849:               nItems = ['thread', 'thimble'];
13852:               nItems = ['thread-thimble', 'forget-me-not'];
13859:               nItems = ['thread', 'thimble'];
13862:               nItems = ['thread-thimble', 'scissors'];
13868:             nItems = ['thread', 'pinstripe'];
13884:               nItems = ['thread', 'thimble'];
13887:               nItems = ['thread-thimble', 'neutron'];
13894:               nItems = ['thread', 'thimble'];
13897:               nItems = ['thread-thimble', 'basket'];
15362:     'intro-finale/items-needle-thread',
15363:     'intro-finale/items-needle',
15404:     'intro-finale/items-thread-thimble',
15405:     'intro-finale/items-thread',
16665:   'intro-finale/items-needle-thread': { width: 68, height: 65, x: 834, y: 0 },
16666:   'intro-finale/items-needle': { top: 8, width: 59, height: 51, x: 904, y: 0 },
16707:   'intro-finale/items-thread-thimble': { left: 2, top: 11, bottom: 14, right: 11, width: 52, height: 40, x: 690, y: 96 },
16708:   'intro-finale/items-thread': { left: 4, top: 16, bottom: 15, right: 13, width: 48, height: 34, x: 744, y: 96 },
github.com/chromium/chromium:native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ master, ]
185:   DWORD thread;			/* Win32 thread ID */
502:   ptw32_thread_t * thread;
158:   HANDLE threadH;		/* Win32 thread handle - POSIX thread is invalid if threadH == 0 */
162:   ptw32_mcs_lock_t threadLock;	/* Used for serialised access to public thread state */
246:   pthread_t ownerThread;
346:   void *threads;
350: typedef struct ThreadParms ThreadParms;
352: struct ThreadParms
401: typedef struct ThreadKeyAssoc ThreadKeyAssoc;
403: struct ThreadKeyAssoc
505:   ThreadKeyAssoc *nextThread;
507:   ThreadKeyAssoc *prevThread;
152: typedef struct ptw32_thread_t_       ptw32_thread_t;
155: struct ptw32_thread_t_
575: #define PTW32_THREAD_REUSE_EMPTY ((ptw32_thread_t *)(size_t) 1)
198: struct pthread_attr_t_
234: struct pthread_mutex_t_
273: struct pthread_mutexattr_t_
302: struct pthread_spinlock_t_
326: struct pthread_barrier_t_
336: struct pthread_barrierattr_t_
341: struct pthread_key_t_
360: struct pthread_cond_t_
378: struct pthread_condattr_t_
385: struct pthread_rwlock_t_
396: struct pthread_rwlockattr_t_
133:   PThreadStateInitial = 0,	/* Thread not running                   */
134:   PThreadStateRunning,		/* Thread alive & kicking               */
135:   PThreadStateSuspended,	/* Thread alive but suspended           */
136:   PThreadStateCancelPending,	/* Thread alive but                     */
138:   PThreadStateCanceling,	/* Thread alive but is                  */
141:   PThreadStateExiting,		/* Thread alive but exiting             */
143:   PThreadStateLast,             /* All handlers have been run and now   */
145:   PThreadStateReuse             /* In reuse pool.                       */
147: PThreadState;
944: #define _beginthreadex(security, \
957: #define _endthreadex ExitThread
129:    * This enumeration represents the state of the thread;
130:    * The thread is still "alive" if the numeric value of the
157:   unsigned __int64 seqNumber;	/* Process-unique thread sequence number */
159:   pthread_t ptHandle;		/* This thread's permanent pthread_t handle */
160:   ptw32_thread_t * prevReuse;	/* Links threads on reuse stack */
242:   int recursive_count;		/* Number of unlocks a thread needs to perform
263:  * Node used to manage per-thread lists of currently-held robust mutexes.
407:    *      This structure creates an association between a thread and a key.
409:    *      destroy routine for thread specific data registered by a user upon
410:    *      exiting a thread.
416:    *         T - Thread that has called pthread_setspecific(Kn)
417:    *            (head of chain is thread->keys)
436:    *      general lock (guarding the row) and the thread's general
440:    *      until both the key is deleted and the thread has called the
442:    *      to be freed as soon as either thread or key is concluded.
445:    *      key and thread locks are acquired consistently in the order
446:    *      "key lock then thread lock". An exception to this exists
447:    *      when a thread calls the destructors, however, this is done
450:    *      An association is created when a thread first calls
455:    *      thread calls the key destructor function on thread exit, or
459:    *      thread
460:    *              reference to the thread that owns the
462:    *              thread struct itself. Since the association is
463:    *              destroyed before the thread exits, this can never
464:    *              point to a different logical thread to the one that
465:    *              created the assoc, i.e. after thread struct reuse.
492:    *      1)      As soon as either the key or the thread is no longer
574: /* Thread Reuse stack bottom marker. Must not be NULL or any valid pointer to memory. */
578: extern ptw32_thread_t * ptw32_threadReuseTop;
579: extern ptw32_thread_t * ptw32_threadReuseBottom;
593: extern ptw32_mcs_lock_t ptw32_thread_reuse_lock;
626:   void ptw32_robust_mutex_remove(pthread_mutex_t* mutex, ptw32_thread_t* otp);
644:   void ptw32_threadReusePush (pthread_t thread);
648:   int ptw32_setthreadpriority (pthread_t thread, int policy, int priority);
659:   void ptw32_callUserDestroyRoutines (pthread_t thread);
661:   int ptw32_tkAssocCreate (ptw32_thread_t * thread, pthread_key_t key);
6:  * Keeps all the internals out of pthread.h
10:  *      Pthreads-win32 - POSIX Threads Library for Win32
224:   pthread_mutex_t lock;
248: 				   threads. */
267:   pthread_mutex_t mx;
308:     pthread_mutex_t mutex;	/* mutex if single cpu.            */
354:   pthread_t tid;
362:   long nWaitersBlocked;		/* Number of threads blocked            */
363:   long nWaitersGone;		/* Number of threads timed out          */
364:   long nWaitersToUnblock;	/* Number of threads to unblock         */
365:   sem_t semBlockQueue;		/* Queue up threads waiting for the     */
370:   pthread_mutex_t mtxUnblockLock;	/* Mutex that guards access to          */
373:   pthread_cond_t next;		/* Doubly linked list                   */
374:   pthread_cond_t prev;
387:   pthread_mutex_t mtxExclusiveAccess;
388:   pthread_mutex_t mtxSharedAccessCompleted;
389:   pthread_cond_t cndSharedAccessCompleted;
415:    *            (head of chain is key->threads)
451:    *      pthread_setspecific() on a key that has a specified
471:    *              The pthread_t->keys attribute is the head of a
474:    *              between a pthread_t and all pthread_key_t on which
475:    *              it called pthread_setspecific.
480:    *      nextThread
481:    *              The pthread_key_t->threads attribute is the head of
484:    *              relationship between a pthread_key_t and all the 
485:    *              PThreads that have called pthread_setspecific for
486:    *              this pthread_key_t.
488:    *      prevThread
497:    *              pthread_setspecific if the user provided a
503:   pthread_key_t key;
504:   ThreadKeyAssoc *nextKey;
506:   ThreadKeyAssoc *prevKey;
571: /* Declared in pthread_cancel.c */
580: extern pthread_key_t ptw32_selfThreadKey;
581: extern pthread_key_t ptw32_cleanupKey;
582: extern pthread_cond_t ptw32_cond_list_head;
583: extern pthread_cond_t ptw32_cond_list_tail;
587: extern unsigned __int64 ptw32_threadSeqNumber;
601: extern int pthread_count;
617:   int ptw32_is_attr (const pthread_attr_t * attr);
619:   int ptw32_cond_check_need_init (pthread_cond_t * cond);
620:   int ptw32_mutex_check_need_init (pthread_mutex_t * mutex);
621:   int ptw32_rwlock_check_need_init (pthread_rwlock_t * rwlock);
622:   int ptw32_spinlock_check_need_init (pthread_spinlock_t * lock);
624:   int ptw32_robust_mutex_inherit(pthread_mutex_t * mutex);
625:   void ptw32_robust_mutex_add(pthread_mutex_t* mutex, pthread_t self);
630: 			       HANDLE threadH, DWORD callback_arg);
636:   void ptw32_threadDestroy (pthread_t tid);
640:   pthread_t ptw32_new (void);
642:   pthread_t ptw32_threadReusePop (void);
657:     ptw32_threadStart (void *vthreadParms);
663:   void ptw32_tkAssocDestroy (ThreadKeyAssoc * assoc);
714:   _CRTIMP unsigned long __cdecl _beginthread (void (__cdecl *) (void *),
716:   _CRTIMP void __cdecl _endthread (void);
937: #if defined(NEED_CREATETHREAD)
940:  * Macro uses args so we can cast start_proc to LPTHREAD_START_ROUTINE
950:         CreateThread(security, \
952:                      (LPTHREAD_START_ROUTINE) start_proc, \
959: #endif				/* NEED_CREATETHREAD */
12:  *      Copyright(C) 1999,2005 Pthreads-win32 contributors
20:  *      http://sources.redhat.com/pthreads-win32/contributors.html
131:    * state is greater or equal "PThreadStateRunning".
161:   volatile PThreadState state;
483:    *              nextThreads link. This chain provides the 1 to many
717:   _CRTIMP unsigned long __cdecl _beginthreadex (void *, unsigned,
720:   _CRTIMP void __cdecl _endthreadex (unsigned);
chromium.googlesource.com/chromium/src:native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ master, ] Duplicate result
chromium.googlesource.com/ios-chromium-mirror:native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ master, ] Duplicate result
android.googlesource.com/platform/external/jetbrains/JetBrainsRuntime:src/hotspot/share/runtime/thread.hpp: [ master, ]
113: class Thread: public ThreadShadow {
286:   void set_suspendible_thread() {
290:   void clear_suspendible_thread() {
294:   bool is_suspendible_thread() { return _suspendible_thread; }
384:     is_definitely_current_thread = true
404:   virtual bool is_VM_thread()       const            { return false; }
405:   virtual bool is_Java_thread()     const            { return false; }
406:   virtual bool is_Compiler_thread() const            { return false; }
407:   virtual bool is_Code_cache_sweeper_thread() const  { return false; }
409:   virtual bool is_jvmti_agent_thread() const         { return false; }
413:   virtual bool is_GC_task_thread() const             { return false; }
414:   virtual bool is_Watcher_thread() const             { return false; }
415:   virtual bool is_ConcurrentGC_thread() const        { return false; }
416:   virtual bool is_Named_thread() const               { return false; }
417:   virtual bool is_Worker_thread() const              { return false; }
423:   virtual WorkerThread* as_Worker_thread() const     { return NULL; }
828:   JavaThread* _processed_thread;
837:   virtual bool is_Named_thread() const { return true; }
839:   JavaThread *processed_thread() { return _processed_thread; }
840:   void set_processed_thread(JavaThread *thread) { _processed_thread = thread; }
853:   virtual bool is_Worker_thread() const { return true; }
855:   virtual WorkerThread* as_Worker_thread() const {
871:   static WatcherThread* _watcher_thread;
890:   bool is_Watcher_thread() const                 { return true; }
898:   static WatcherThread* watcher_thread()         { return _watcher_thread; }
1180:   virtual bool is_Java_thread() const            { return true;  }
1222:   JavaThreadState thread_state() const           { return _thread_state; }
1713:   static ByteSize thread_state_offset()          { return byte_offset_of(JavaThread, _thread_state); }
1741:   static JavaThread* thread_from_jni_environment(JNIEnv* env) {
2069:   bool is_Code_cache_sweeper_thread() const { return true; }
2098:   bool is_Compiler_thread() const                { return true; }
2203:   static int thread_claim_parity() { return _thread_claim_parity; }
2269:   Thread* _thread;
506:   OSThread* osthread() const                     { return _osthread;   }
507:   void set_osthread(OSThread* thread)            { _osthread = thread; }
616:   OSThread* _osthread;  // Platform-specific thread information
780: class NonJavaThread: public Thread {
820: class NamedThread: public NonJavaThread {
848: class WorkerThread: public NamedThread {
852:   WorkerThread() : _id(0)               { }
865: class WatcherThread: public NonJavaThread {
885:   ~WatcherThread() {
913: typedef void (*ThreadFunction)(JavaThread*, TRAPS);
915: class JavaThread: public Thread {
1189:   oop threadObj() const                          { return _threadObj; }
1283:   void handshake_process_by_vmthread() {
1692:   static ByteSize threadObj_offset()             { return byte_offset_of(JavaThread, _threadObj); }
2050: inline CompilerThread* JavaThread::as_CompilerThread() {
2056: class CodeCacheSweeperThread : public JavaThread {
2077: class CompilerThread : public JavaThread {
2150: class Threads: AllStatic {
2262: class ThreadClosure: public StackObj {
26: #define SHARE_VM_RUNTIME_THREAD_HPP
445:   void set_native_thread_name(const char *name) {
921:   bool           _on_thread_list;                // Is set when this JavaThread is added to the Threads list
1000:   volatile JavaThreadState _thread_state;
1008:     _thread_exiting,                             // JavaThread::exit() has been called for this thread
1009:     _thread_terminated,                          // JavaThread is removed from thread list
1087:   static jlong* _jvmci_old_thread_counters;
1223:   void set_thread_state(JavaThreadState s)       { _thread_state = s;    }
1236:   bool on_thread_list() const { return _on_thread_list; }
1237:   void set_on_thread_list() { _on_thread_list = true; }
1899:   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
1907:   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
1908:   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1961:   JvmtiThreadState *_jvmti_thread_state;
1990:   ThreadStatistics *_thread_stat;
1993:   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
2153:   static JavaThread* _thread_list;
2157:   static int         _thread_claim_parity;
155:   ThreadsList* volatile _threads_hazard_ptr;
156:   SafeThreadsListPtr*   _threads_list_ptr;
170:   uint _nested_threads_hazard_ptr_cnt;
171:   void dec_nested_threads_hazard_ptr_cnt() {
175:   void inc_nested_threads_hazard_ptr_cnt() {
178:   uint nested_threads_hazard_ptr_cnt() {
922:   oop            _threadObj;                     // The Java level thread object
1190:   void set_threadObj(oop p)                      { _threadObj = p; }
1715:   static ByteSize osthread_offset()              { return byte_offset_of(JavaThread, _osthread); }
2154:   static int         _number_of_threads;
2155:   static int         _number_of_non_daemon_threads;
2252:   static int number_of_threads()                 { return _number_of_threads; }
2254:   static int number_of_non_daemon_threads()      { return _number_of_non_daemon_threads; }
25: #ifndef SHARE_VM_RUNTIME_THREAD_HPP
96: // - Thread
109: // All Thread subclasses must be either JavaThread or NonJavaThread.
110: // This means !t->is_Java_thread() iff t is a NonJavaThread, or t is
111: // a partially constructed/destroyed Thread.
119:   // Current thread is maintained as a thread-local variable
120:   static THREAD_LOCAL_DECL Thread* _thr_current;
124:   // Thread local data area available to the GC. The internal
131:     return byte_offset_of(Thread, _gc_data);
141:   //oop       _pending_exception;                // pending exception for current thread
145:   // Support for forcing alignment of thread objects for biased locking
212:   // flag is checked by has_special_runtime_exit_condition() and java thread
214:   // called. Most uses of the _thread_blocked state in JavaThreads are
218:   //   + mutex granting (do not enter monitors when thread is suspended)
219:   //   + state transitions from _thread_in_native
227:   // followed by some other interface call that requires the thread to
261:     _external_suspend       = 0x20000000U, // thread is asked to self suspend
262:     _ext_suspended          = 0x40000000U, // thread has self-suspended
263:     _deopt_suspend          = 0x10000000U, // thread needs to self suspend for deopt
278:   DEBUG_ONLY(bool _suspendible_thread;)
287:     _suspendible_thread = true;
291:     _suspendible_thread = false;
301:   // One-element thread local free list
307:   // The parity of the last strong_roots iteration in which this thread was
333:   NOT_PRODUCT(int _allow_safepoint_count;)      // If 0, thread allow a safepoint to happen
334:   debug_only(int _allow_allocation_count;)     // If 0, the thread is allowed to allocate oops.
344:   volatile void* _polling_page;                 // Thread local polling page
346:   ThreadLocalAllocBuffer _tlab;                 // Thread-local eden
351:   ThreadStatisticalInfo _statistical_info;      // Statistics about the thread
353:   JFR_ONLY(DEFINE_THREAD_LOCAL_FIELD_JFR;)      // Thread-local data for jfr
358:   ObjectMonitor* _current_pending_monitor;      // ObjectMonitor this thread
362:   // ObjectMonitor on which this thread called Object.wait()
365:   // Private thread-local objectmonitor list - a simple cache organized as a SLL.
388:   Thread();
389:   virtual ~Thread() = 0;        // Thread is abstract.
391:   // Manage Thread::current()
392:   void initialize_thread_current();
393:   static void clear_thread_current(); // TLS cleanup needed before threads terminate
410:   // True iff the thread can perform GC operations at a safepoint.
411:   // Generally will be true only of VM thread and parallel GC WorkGang
419:   // Can this thread make Java upcalls
425:   virtual char* name() const { return (char*)"Unknown thread"; }
427:   // Returns the current thread (ASSERTS if NULL)
428:   static inline Thread* current();
429:   // Returns the current thread, or NULL if not attached
430:   static inline Thread* current_or_null();
431:   // Returns the current thread, or NULL if not attached, and is
433:   static inline Thread* current_or_null_safe();
435:   // Common thread operations
437:   static void check_for_dangling_thread_pointer(Thread *thread);
439:   static void set_priority(Thread* thread, ThreadPriority priority);
440:   static ThreadPriority get_priority(const Thread* const thread);
441:   static void start(Thread* thread);
442:   static void interrupt(Thread* thr);
443:   static bool is_interrupted(Thread* thr, bool clear_interrupted);
446:     assert(Thread::current() == this, "set_native_thread_name can only be called on the current thread");
447:     os::set_native_thread_name(name);
471:   // Thread's fields layout the same.
500:   static void send_async_exception(oop thread_oop, oop java_throwable);
522:   // Thread-Local Allocation Buffer (TLAB) support
539:   JFR_ONLY(DEFINE_THREAD_LOCAL_ACCESSOR_JFR;)
548:   // For tracking the heavyweight monitor the thread is pending on.
562:   // For tracking the ObjectMonitor on which this thread called Object.wait()
585:   // calling thread does the update, this indicates that the calling thread
586:   // has claimed the thread's stack as a root groop in the current
603:   // Check if address is in the stack of the thread (not just for locks).
604:   // Warning: the method can only be used on the running thread
610:   // Sets this thread as starting thread. Returns failure if thread
612:   bool set_as_starting_thread();
615:   // OS data associated with the thread
618:   // Thread local resource area for temporary allocation within the VM
623:   // Thread local handle area for allocation of handles within the VM
627:   // Support for stack overflow handling, get_thread, etc.
630:   uintptr_t        _self_raw_id;      // used by get_thread (mutable)
643:   void    register_thread_stack_with_NMT() NOT_NMT_RETURN;
666:   // Deadlock detection support for Mutex locks. List of locks own by thread.
698:   static ByteSize exception_file_offset()        { return byte_offset_of(Thread, _exception_file); }
699:   static ByteSize exception_line_offset()        { return byte_offset_of(Thread, _exception_line); }
700:   static ByteSize active_handles_offset()        { return byte_offset_of(Thread, _active_handles); }
702:   static ByteSize stack_base_offset()            { return byte_offset_of(Thread, _stack_base); }
703:   static ByteSize stack_size_offset()            { return byte_offset_of(Thread, _stack_size); }
705:   static ByteSize polling_page_offset()          { return byte_offset_of(Thread, _polling_page); }
708:   static ByteSize tlab_##name##_offset()         { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::name##_offset(); }
722:   static ByteSize allocated_bytes_offset()       { return byte_offset_of(Thread, _allocated_bytes); }
724:   JFR_ONLY(DEFINE_THREAD_LOCAL_OFFSET_JFR;)
730:   ParkEvent * _SleepEvent;                    // for Thread.sleep
736:   jint _hashStateW;                           // Marsaglia Shift-XOR thread-local RNG
737:   jint _hashStateX;                           // thread-specific hashCode generator state
755: // Inline implementation of Thread::current()
756: inline Thread* Thread::current() {
757:   Thread* current = current_or_null();
758:   assert(current != NULL, "Thread::current() called on detached thread");
762: inline Thread* Thread::current_or_null() {
767:     return ThreadLocalStorage::thread();
773: inline Thread* Thread::current_or_null_safe() {
775:     return ThreadLocalStorage::thread();
829:   uint _gc_id; // The current GC id when a thread takes part in GC
834:   // May only be called once per thread.
836:   void initialize_named_thread();
838:   virtual char* name() const { return _name == NULL ? (char*)"Unknown Thread" : _name; }
856:     assert(is_Worker_thread(), "Dubious cast to WorkerThread*?");
893:   char* name() const { return (char*)"VM Periodic Task Thread"; }
920:   JavaThread*    _next;                          // The next thread in the Threads list
999:  public:                                         // Expose _thread_state for SafeFetchInt()
1002:   ThreadSafepointState *_safepoint_state;        // Holds information about a thread during a safepoint
1016:   //   _not_terminated => _thread_exiting => _thread_terminated
1024:                                                  // handlers thread is in
1025:   volatile bool         _doing_unsafe_access;    // Thread may fault due to unsafe access
1031:     _not_attaching_via_jni = 1,  // thread is not attaching via JNI
1032:     _attaching_via_jni,          // thread is attaching via JNI
1033:     _attached_via_jni            // thread has attached via JNI
1037:   // A native thread that is attaching via JNI starts with a value
1042:   // State of the stack guard pages for this thread.
1083:   // Support for high precision, thread sensitive counters in JVMCI compiled code.
1146:   JavaThread(bool is_attaching_via_jni = false); // for main thread and JNI attached threads
1163:   // This function is called at thread creation to allow
1164:   // platform specific thread variables to be initialized.
1170:   // Cleanup on thread exit
1177:   void cleanup_failed_attach_current_thread();
1183:   // Thread chain operations
1187:   // Thread oop. threadObj() can be NULL for initial JavaThread
1194:   // Prepare thread and add to priority queue.  If a priority is
1195:   // not specified, use the priority of the thread object. Threads_lock
1197:   void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
1205:   // Allocates a new Java level thread object for this thread. thread_name may be NULL.
1206:   void allocate_threadObj(Handle thread_group, const char* thread_name, bool daemon, TRAPS);
1225:   // Use membars when accessing volatile _thread_state. See
1227:   inline JavaThreadState thread_state() const;
1228:   inline void set_thread_state(JavaThreadState s);
1239:   // thread has called JavaThread::exit() or is terminated
1241:   // thread is terminated (no longer on the threads list); we compare
1245:     return l_terminated != _not_terminated && l_terminated != _thread_exiting;
1264:   // Support for thread handshake operations
1305:         // don't surprise the thread that suspended us by returning
1311:   static void check_safepoint_and_suspend_for_native_trans(JavaThread *thread);
1313:   static void check_special_condition_for_native_trans(JavaThread *thread);
1316:   // transition into thread_in_Java mode so that it can potentially
1318:   static void check_special_condition_for_native_trans_and_transition(JavaThread *thread);
1324:     // SR_lock to allow the thread to reach a stable thread state if
1325:     // it is currently in a transient thread state.
1339:   bool is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits);
1351:   // Whenever a thread transitions from native to vm/java it must suspend
1398:   // Thread.stop support
1399:   void send_thread_stop(oop throwable);
1666:   // Returns true if (a) guard pages are not needed on this thread, (b) the
1738:   // Returns the jni environment for this thread
1742:     JavaThread *thread_from_jni_env = (JavaThread*)((intptr_t)env - in_bytes(jni_environment_offset()));
1743:     // Only return NULL if thread is off the thread list; starting to
1745:     if (thread_from_jni_env->is_terminated()) {
1746:       thread_from_jni_env->block_if_vm_exited();
1749:       return thread_from_jni_env;
1757:     assert(Thread::current() == this ||
1758:            (Thread::current()->is_VM_thread() &&
1760:            "this must be current thread or synchronizing");
1764:     assert(Thread::current() == this, "this must be current thread");
1817:   char* name() const { return (char*)get_thread_name(); }
1821:   void print_thread_state_on(outputStream*) const      PRODUCT_RETURN;
1822:   void print_thread_state() const                      PRODUCT_RETURN;
1826:   const char* get_thread_name() const;
1829:   const char* get_thread_name_string(char* buf = NULL, int buflen = 0) const;
1871:   // Returns the running thread as a JavaThread
1874:   // Returns the active Java thread.  Do not use this if you know you are calling
1884:   void thread_main_inner();
1898:   // Thread local information maintained by JVMTI.
1900:   // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1979:   // support for cached flag that indicates whether exceptions need to be posted for this thread
1995:   // Return a blocker object for which this thread is blocked parking.
2010: #include OS_CPU_HEADER(thread)
2024:   // JSR166 per-thread parker
2045:   Thread* thread = Thread::current();
2046:   assert(thread->is_Java_thread(), "just checking");
2047:   return (JavaThread*)thread;
2051:   assert(is_Compiler_thread(), "just checking");
2055: // Dedicated thread to sweep the code cache
2066:   // Hide sweeper thread from external view.
2076: // A thread used for Compilation.
2111:   // Get/set the thread's compilation environment.
2118:   // Get/set the thread's logging information
2139:   // Get/set the thread's current task
2148: // The active thread queue. It also keeps track of the current used
2149: // thread priorities.
2162:   static void initialize_java_lang_classes(JavaThread* main_thread, TRAPS);
2166:   // Thread management
2168:   // thread to the thread list before allocating its thread object
2173:   static void java_threads_and_vm_thread_do(ThreadClosure* tc);
2177:   // Initializes the vm and creates the vm thread
2190:   // The "thread claim parity" provides a way for threads to be claimed
2193:   // Each thread contains a a "parity" field. A task will claim the
2194:   // thread only if its parity field is the same as the global parity,
2195:   // which is updated by calling change_thread_claim_parity().
2197:   // For this to work change_thread_claim_parity() needs to be called
2201:   // New threads get their parity set to 0 and change_thread_claim_parity()
2204:   static void change_thread_claim_parity();
2238:   static void print_on_error(outputStream* st, Thread* current, char* buf, int buflen);
2239:   static void print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
2247:   // Get owning Java thread from the monitor's owner field.
2248:   static JavaThread *owning_thread_from_monitor_owner(ThreadsList * t_list,
2261: // Thread iterator
2264:   virtual void do_thread(Thread* thread) = 0;
2271:   SignalHandlerMark(Thread* t) {
2272:     _thread = t;
2273:     if (_thread) _thread->enter_signal_handler();
2276:     if (_thread) _thread->leave_signal_handler();
2277:     _thread = NULL;
2282: #endif // SHARE_VM_RUNTIME_THREAD_HPP
30: #include "gc/shared/threadLocalAllocBuffer.hpp"
41: #include "runtime/osThread.hpp"
45: #include "runtime/threadHeapSampler.hpp"
46: #include "runtime/threadLocalStorage.hpp"
47: #include "runtime/threadStatisticalInfo.hpp"
61: class ThreadSafepointState;
62: class ThreadsList;
63: class ThreadsSMRSupport;
67: class ThreadStatistics;
73: class CompileThread;
84: class ThreadClosure;
93: class WorkerThread;
97: //   - JavaThread
98: //     - various subclasses eg CompilerThread, ServiceThread
99: //   - NonJavaThread
100: //     - NamedThread
101: //       - VMThread
102: //       - ConcurrentGCThread
103: //       - WorkerThread
105: //         - GCTaskThread
106: //     - WatcherThread
140:   // (Note: _pending_exception and friends are in ThreadShadow)
148:   // JavaThread lifecycle support:
149:   friend class SafeThreadsListPtr;  // for _threads_list_ptr, cmpxchg_threads_hazard_ptr(), {dec_,inc_,}nested_threads_hazard_ptr_cnt(), {g,s}et_threads_hazard_ptr(), inc_nested_handle_cnt(), tag_hazard_ptr() access
150:   friend class ScanHazardPtrGatherProtectedThreadsClosure;  // for cmpxchg_threads_hazard_ptr(), get_threads_hazard_ptr(), is_hazard_ptr_tagged() access
151:   friend class ScanHazardPtrGatherThreadsListClosure;  // for get_threads_hazard_ptr(), untag_hazard_ptr() access
152:   friend class ScanHazardPtrPrintMatchingThreadsClosure;  // for get_threads_hazard_ptr(), is_hazard_ptr_tagged() access
153:   friend class ThreadsSMRSupport;  // for _nested_threads_hazard_ptr_cnt, _threads_hazard_ptr, _threads_list_ptr access
157:   ThreadsList*          cmpxchg_threads_hazard_ptr(ThreadsList* exchange_value, ThreadsList* compare_value);
158:   ThreadsList*          get_threads_hazard_ptr();
159:   void                  set_threads_hazard_ptr(ThreadsList* new_list);
160:   static bool           is_hazard_ptr_tagged(ThreadsList* list) {
163:   static ThreadsList*   tag_hazard_ptr(ThreadsList* list) {
164:     return (ThreadsList*)(intptr_t(list) | intptr_t(1));
166:   static ThreadsList*   untag_hazard_ptr(ThreadsList* list) {
167:     return (ThreadsList*)(intptr_t(list) & ~intptr_t(1));
172:     assert(_nested_threads_hazard_ptr_cnt != 0, "mismatched {dec,inc}_nested_threads_hazard_ptr_cnt()");
173:     _nested_threads_hazard_ptr_cnt--;
176:     _nested_threads_hazard_ptr_cnt++;
179:     return _nested_threads_hazard_ptr_cnt;
189:   static void* allocate(size_t size, bool throw_excpt, MEMFLAGS flags = mtThread);
202:   // External suspend/resume requests come from JVM_SuspendThread,
203:   // JVM_ResumeThread, JVMTI SuspendThread, and finally JVMTI
204:   // ResumeThread. External
209:   // for already suspended threads.
216:   // condition lifts, the JavaThread will self-suspend. Other places
229:   // the interface that requires quiescence, we give the JavaThread a
244:   // 1. The suspend/resume logic no longer uses ThreadState in OSThread
246:   // JVMTI) happy. ThreadState is legacy code (see notes in
247:   // osThread.hpp).
349:   ThreadHeapSampler _heap_sampler;              // For use when sampling the memory.
412:   // threads.
523:   ThreadLocalAllocBuffer& tlab()                 { return _tlab; }
535:   ThreadHeapSampler& heap_sampler()     { return _heap_sampler; }
537:   ThreadStatisticalInfo& statistical_info() { return _statistical_info; }
572:   //   Used by JavaThread::oops_do.
583:   // uses an atomic instruction to set the current threads parity to
611:   // creation fails due to lack of memory, too many threads etc.
766:   if (ThreadLocalStorage::is_initialized()) {
774:   if (ThreadLocalStorage::is_initialized()) {
783:   NonJavaThread* volatile _next;
789:   NonJavaThread();
790:   ~NonJavaThread();
796: // management occurs in the NonJavaThread constructor and destructor,
798: // derived class.  Threads created after an iterator is constructed
801: class NonJavaThread::Iterator : public StackObj {
803:   NonJavaThread* _current;
814:   NonJavaThread* current() const { return _current; }
818: // Name support for threads.  non-JavaThread subclasses with multiple
827:   // log JavaThread being processed by oops_do
832:   NamedThread();
833:   ~NamedThread();
847: // Worker threads are named and have an id of an assigned work.
857:     return (WorkerThread*) this;
864: // A single WatcherThread is used for simulating timer interrupts.
882:   WatcherThread();
886:     guarantee(false, "WatcherThread deletion must fix the race with VM termination");
897:   // Returns the single instance of WatcherThread
900:   // Create and start the single instance of WatcherThread, or stop it on shutdown
911: class CompilerThread;
948:   ThreadFunction _entry_point;
1005:   // JavaThread termination support
1010:     _vm_exited                                   // JavaThread is still executing native code, but VM is terminated
1014:   // In general a JavaThread's _terminated field transitions as follows:
1018:   // _vm_exited is a special value to cover the case of a JavaThread
1036:   // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni.
1138:   friend class VMThread;
1139:   friend class ThreadWaitTransition;
1147:   JavaThread(ThreadFunction entry_point, size_t stack_size = 0);
1148:   ~JavaThread();
1151:   // verify this JavaThread hasn't be published in the Threads::list yet
1184:   JavaThread* next() const                       { return _next; }
1185:   void set_next(JavaThread* p)                   { _next = p; }
1188:   // (or for threads attached via JNI)
1192:   ThreadPriority java_priority() const;          // Read from threadObj()
1203:   ThreadFunction entry_point() const             { return _entry_point; }
1226:   // Threads::create_vm() for size checks.
1230:   ThreadSafepointState *safepoint_state() const  { return _safepoint_state; }
1231:   void set_safepoint_state(ThreadSafepointState *state) { _safepoint_state = state; }
1234:   // JavaThread termination and lifecycle support:
1242:   // against the two non-terminated values so that a freed JavaThread
1249:   // special for Threads::remove() which is static:
1284:     _handshake.process_by_vmthread(this);
1287:   // Suspend/resume support for JavaThread
1298:     assert(JavaThread::current() == this, "sanity check");
1414:   // Return true if JavaThread has an asynchronous condition or
1679:       stack_end() + MAX2(JavaThread::stack_guard_zone_size(), JavaThread::stack_shadow_zone_size());
1694:   static ByteSize jmp_ring_index_offset()        { return byte_offset_of(JavaThread, _jmp_ring_index); }
1695:   static ByteSize jmp_ring_offset()              { return byte_offset_of(JavaThread, _jmp_ring); }
1697:   static ByteSize jni_environment_offset()       { return byte_offset_of(JavaThread, _jni_environment); }
1699:     return byte_offset_of(JavaThread, _pending_jni_exception_check_fn);
1702:     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
1705:     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
1708:     return byte_offset_of(JavaThread, _anchor);
1710:   static ByteSize callee_target_offset()         { return byte_offset_of(JavaThread, _callee_target); }
1711:   static ByteSize vm_result_offset()             { return byte_offset_of(JavaThread, _vm_result); }
1712:   static ByteSize vm_result_2_offset()           { return byte_offset_of(JavaThread, _vm_result_2); }
1714:   static ByteSize saved_exception_pc_offset()    { return byte_offset_of(JavaThread, _saved_exception_pc); }
1717:   static ByteSize pending_deoptimization_offset() { return byte_offset_of(JavaThread, _pending_deoptimization); }
1718:   static ByteSize pending_monitorenter_offset()  { return byte_offset_of(JavaThread, _pending_monitorenter); }
1719:   static ByteSize pending_failed_speculation_offset() { return byte_offset_of(JavaThread, _pending_failed_speculation); }
1720:   static ByteSize jvmci_alternate_call_target_offset() { return byte_offset_of(JavaThread, _jvmci._alternate_call_target); }
1721:   static ByteSize jvmci_implicit_exception_pc_offset() { return byte_offset_of(JavaThread, _jvmci._implicit_exception_pc); }
1722:   static ByteSize jvmci_counters_offset()        { return byte_offset_of(JavaThread, _jvmci_counters); }
1724:   static ByteSize exception_oop_offset()         { return byte_offset_of(JavaThread, _exception_oop); }
1725:   static ByteSize exception_pc_offset()          { return byte_offset_of(JavaThread, _exception_pc); }
1726:   static ByteSize exception_handler_pc_offset()  { return byte_offset_of(JavaThread, _exception_handler_pc); }
1727:   static ByteSize stack_overflow_limit_offset()  { return byte_offset_of(JavaThread, _stack_overflow_limit); }
1728:   static ByteSize is_method_handle_return_offset() { return byte_offset_of(JavaThread, _is_method_handle_return); }
1729:   static ByteSize stack_guard_state_offset()     { return byte_offset_of(JavaThread, _stack_guard_state); }
1730:   static ByteSize reserved_stack_activation_offset() { return byte_offset_of(JavaThread, _reserved_stack_activation); }
1731:   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags); }
1733:   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
1735:     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
1773:   // within ThreadToNativeFromVM makes proper exception checks (i.e. VM internal).
1800:   void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; }
1831:   const char* get_threadgroup_name() const;
1872:   static inline JavaThread* current();
1875:   // from a JavaThread, as it's slower than JavaThread::current.  If called from
1876:   // the VMThread, it also returns the JavaThread that instigated the VMThread's
1878:   static JavaThread* active();
1880:   inline CompilerThread* as_CompilerThread();
1901:   // getter is used to get this JavaThread's JvmtiThreadState if it has
1903:   // is used to get the specified JavaThread's JvmtiThreadState if it has
1904:   // one or it allocates a new JvmtiThreadState for the JavaThread and
1906:   // the specified JavaThread is exiting.
1930:   static ByteSize popframe_condition_offset()         { return byte_offset_of(JavaThread, _popframe_condition); }
1973:   static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
2043: // Inline implementation of JavaThread::current
2044: inline JavaThread* JavaThread::current() {
2052:   return (CompilerThread*)this;
2059:   CodeCacheSweeperThread();
2084:   CompileTask* volatile _task;  // print_threads_compiling can read this concurrently.
2093:   static CompilerThread* current();
2095:   CompilerThread(CompileQueue* queue, CompilerCounters* counters);
2096:   ~CompilerThread();
2102:   // Hide native compiler threads from external view.
2144: inline CompilerThread* CompilerThread::current() {
2145:   return JavaThread::current()->as_CompilerThread();
2169:   static void add(JavaThread* p, bool force_daemon = false);
2170:   static void remove(JavaThread* p);
2171:   static void non_java_threads_do(ThreadClosure* tc);
2172:   static void java_threads_do(ThreadClosure* tc);
2174:   static void threads_do(ThreadClosure* tc);
2175:   static void possibly_parallel_threads_do(bool is_par, ThreadClosure* tc);
2199:   // that should claim threads.
2205:   static void assert_all_threads_claimed() NOT_DEBUG_RETURN;
2207:   // Apply "f->do_oop" to all root oops in all threads.
2213:   // Apply "f->do_oop" to roots in all threads that
2241:   static void print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form = false);
2243:   // Get Java threads that are waiting to enter a monitor.
2244:   static GrowableArray<JavaThread*>* get_pending_threads(ThreadsList * t_list,
2251:   // Number of threads on the active threads list
2253:   // Number of non-daemon threads on the active threads list
29: #include "gc/shared/gcThreadLocalData.hpp"
56: #include "jfr/support/jfrThreadExtension.hpp"
60: class SafeThreadsListPtr;
65: class JvmtiThreadState;
107: //     - JfrThreadSampler
127:   GCThreadLocalData _gc_data;
169:   // This field is enabled via -XX:+EnableThreadSMRStatistics:
400:   // invokes <ChildThreadClass>::run(), with common preparations and cleanups.
795: // Provides iteration over the list of NonJavaThreads.  Because list
1902:   // one which means NULL can be returned. JvmtiThreadState::state_for()
1905:   // returns it. JvmtiThreadState::state_for() will return NULL only if
android.googlesource.com/platform/external/jetbrains/jdk8u_hotspot:src/share/vm/runtime/thread.hpp: [ master, ]
102: class Thread: public ThreadShadow {
296:     is_definitely_current_thread = true
310:   virtual bool is_VM_thread()       const            { return false; }
311:   virtual bool is_Java_thread()     const            { return false; }
312:   virtual bool is_Compiler_thread() const            { return false; }
314:   virtual bool is_jvmti_agent_thread() const         { return false; }
318:   virtual bool is_GC_task_thread() const             { return false; }
319:   virtual bool is_Watcher_thread() const             { return false; }
320:   virtual bool is_ConcurrentGC_thread() const        { return false; }
321:   virtual bool is_Named_thread() const               { return false; }
322:   virtual bool is_Worker_thread() const              { return false; }
325:   virtual WorkerThread* as_Worker_thread() const     { return NULL; }
690:   JavaThread* _processed_thread;
697:   virtual bool is_Named_thread() const { return true; }
699:   JavaThread *processed_thread() { return _processed_thread; }
700:   void set_processed_thread(JavaThread *thread) { _processed_thread = thread; }
709:   virtual bool is_Worker_thread() const { return true; }
711:   virtual WorkerThread* as_Worker_thread() const {
727:   static WatcherThread* _watcher_thread;
742:   bool is_Watcher_thread() const                 { return true; }
751:   static WatcherThread* watcher_thread()         { return _watcher_thread; }
1010:   virtual bool is_Java_thread() const            { return true;  }
1052:   JavaThreadState thread_state() const           { return _thread_state; }
1363:   static ByteSize thread_state_offset()          { return byte_offset_of(JavaThread, _thread_state        ); }
1387:   static JavaThread* thread_from_jni_environment(JNIEnv* env) {
1842:   bool is_Compiler_thread() const                { return true; }
2006:   Thread* _thread;
415:   OSThread* osthread() const                     { return _osthread;   }
416:   void set_osthread(OSThread* thread)            { _osthread = thread; }
529:   OSThread* _osthread;  // Platform-specific thread information
682: class NamedThread: public Thread {
704: class WorkerThread: public NamedThread {
708:   WorkerThread() : _id(0)               { }
721: class WatcherThread: public Thread {
775: typedef void (*ThreadFunction)(JavaThread*, TRAPS);
777: class JavaThread: public Thread {
1018:   oop threadObj() const                          { return _threadObj; }
1345:   static ByteSize threadObj_offset()             { return byte_offset_of(JavaThread, _threadObj           ); }
1787: inline CompilerThread* JavaThread::as_CompilerThread() {
1822: class CompilerThread : public JavaThread {
1898: class Threads: AllStatic {
1999: class ThreadClosure: public StackObj {
26: #define SHARE_VM_RUNTIME_THREAD_HPP
339:   void set_native_thread_name(const char *name) {
859:   volatile JavaThreadState _thread_state;
867:     _thread_exiting,                             // JavaThread::exit() has been called for this thread
868:     _thread_terminated,                          // JavaThread is removed from thread list
1053:   void set_thread_state(JavaThreadState s)       { _thread_state = s;    }
1517:    ThreadProfiler* _thread_profiler;
1522:    ThreadProfiler* get_thread_profiler()         { return _thread_profiler; }
1523:    ThreadProfiler* set_thread_profiler(ThreadProfiler* tp) {
1558:   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
1566:   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
1567:   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1620:   JvmtiThreadState *_jvmti_thread_state;
1649:   ThreadStatistics *_thread_stat;
1652:   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
1901:   static JavaThread* _thread_list;
781:   oop            _threadObj;                     // The Java level thread object
1019:   void set_threadObj(oop p)                      { _threadObj = p; }
1365:   static ByteSize osthread_offset()              { return byte_offset_of(JavaThread, _osthread            ); }
1902:   static int         _number_of_threads;
1903:   static int         _number_of_non_daemon_threads;
1986:   static int number_of_threads()                 { return _number_of_threads; }
1988:   static int number_of_non_daemon_threads()      { return _number_of_non_daemon_threads; }
25: #ifndef SHARE_VM_RUNTIME_THREAD_HPP
43: #include "runtime/thread_ext.hpp"
92: // - Thread
107:   //oop       _pending_exception;                // pending exception for current thread
111:   // Support for forcing alignment of thread objects for biased locking
143:   // flag is checked by has_special_runtime_exit_condition() and java thread
145:   // called. Most uses of the _thread_blocked state in JavaThreads are
149:   //   + mutex granting (do not enter monitors when thread is suspended)
150:   //   + state transitions from _thread_in_native
158:   // followed by some other interface call that requires the thread to
193:     _external_suspend       = 0x20000000U, // thread is asked to self suspend
194:     _ext_suspended          = 0x40000000U, // thread has self-suspended
195:     _deopt_suspend          = 0x10000000U, // thread needs to self suspend for deopt
215:   static void trace(const char* msg, const Thread* const thread) PRODUCT_RETURN;
220:   // One-element thread local free list
226:   // The parity of the last strong_roots iteration in which this thread was
244:   NOT_PRODUCT(int _allow_safepoint_count;)      // If 0, thread allow a safepoint to happen
245:   debug_only (int _allow_allocation_count;)     // If 0, the thread is allowed to allocate oops.
256:   ThreadLocalAllocBuffer _tlab;                 // Thread-local eden
260:   // Thread-local buffer used by MetadataOnStackMark.
263:   TRACE_DATA _trace_data;                       // Thread-local data for tracing
270:   ObjectMonitor* _current_pending_monitor;      // ObjectMonitor this thread
274:   // ObjectMonitor on which this thread called Object.wait()
277:   // Private thread-local objectmonitor list - a simple cache organized as a SLL.
300:   Thread();
301:   virtual ~Thread();
304:   void initialize_thread_local_storage();
306:   // thread entry point
315:   // True iff the thread can perform GC operations at a safepoint.
316:   // Generally will be true only of VM thread and parallel GC WorkGang
327:   virtual char* name() const { return (char*)"Unknown thread"; }
329:   // Returns the current thread
330:   static inline Thread* current();
332:   // Common thread operations
333:   static void set_priority(Thread* thread, ThreadPriority priority);
334:   static ThreadPriority get_priority(const Thread* const thread);
335:   static void start(Thread* thread);
336:   static void interrupt(Thread* thr);
337:   static bool is_interrupted(Thread* thr, bool clear_interrupted);
340:     assert(Thread::current() == this, "set_native_thread_name can only be called on the current thread");
341:     os::set_native_thread_name(name);
409:   static void send_async_exception(oop thread_oop, oop java_throwable);
431:   // Thread-Local Allocation Buffer (TLAB) support
454:   // For tracking the heavyweight monitor the thread is pending on.
468:   // For tracking the ObjectMonitor on which this thread called Object.wait()
492:   // calling thread does the update, this indicates that the calling thread
493:   // has claimed the thread's stack as a root groop in the current
513:   // Check if address is in the stack of the thread (not just for locks).
514:   // Warning: the method can only be used on the running thread
520:   // Sets this thread as starting thread. Returns failure if thread
522:   bool set_as_starting_thread();
528:   // OS data associated with the thread
531:   // Thread local resource area for temporary allocation within the VM
536:   // Thread local handle area for allocation of handles within the VM
540:   // Support for stack overflow handling, get_thread, etc.
543:   uintptr_t        _self_raw_id;      // used by get_thread (mutable)
574:   // Deadlock detection support for Mutex locks. List of locks own by thread.
605:   static ByteSize exception_file_offset()        { return byte_offset_of(Thread, _exception_file   ); }
606:   static ByteSize exception_line_offset()        { return byte_offset_of(Thread, _exception_line   ); }
607:   static ByteSize active_handles_offset()        { return byte_offset_of(Thread, _active_handles   ); }
609:   static ByteSize stack_base_offset()            { return byte_offset_of(Thread, _stack_base ); }
610:   static ByteSize stack_size_offset()            { return byte_offset_of(Thread, _stack_size ); }
613:   static ByteSize tlab_##name##_offset()         { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::name##_offset(); }
627:   static ByteSize allocated_bytes_offset()       { return byte_offset_of(Thread, _allocated_bytes ); }
633:   ParkEvent * _SleepEvent ;                    // for Thread.sleep
639:   jint _hashStateW ;                           // Marsaglia Shift-XOR thread-local RNG
640:   jint _hashStateX ;                           // thread-specific hashCode generator state
658: // Inline implementation of Thread::current()
659: // Thread::current is "hot" it's called > 128K times in the 1st 500 msecs of
661: // ThreadLocalStorage::thread is warm -- it's called > 16K times in the same
662: // period.   This is inlined in thread_<os_family>.inline.hpp.
664: inline Thread* Thread::current() {
669:   // Signal handler should call ThreadLocalStorage::get_thread_slow()
670:   Thread* t = ThreadLocalStorage::get_thread_slow();
672:          "Don't use Thread::current() inside signal handler");
675:   Thread* thread = ThreadLocalStorage::thread();
676:   assert(thread != NULL, "just checking");
677:   return thread;
695:   // May only be called once per thread.
698:   virtual char* name() const { return _name == NULL ? (char*)"Unknown Thread" : _name; }
712:     assert(is_Worker_thread(), "Dubious cast to WorkerThread*?");
745:   char* name() const { return (char*)"VM Periodic Task Thread"; }
761:     assert(Thread::current()->is_Watcher_thread(), "Can only be set by WatcherThread");
780:   JavaThread*    _next;                          // The next thread in the Threads list
858:  public:                                         // Expose _thread_state for SafeFetchInt()
861:   ThreadSafepointState *_safepoint_state;        // Holds information about a thread during a safepoint
875:   //   _not_terminated => _thread_exiting => _thread_terminated
883:                                                  // handlers thread is in
884:   volatile bool         _doing_unsafe_access;    // Thread may fault due to unsafe access
890:     _not_attaching_via_jni = 1,  // thread is not attaching via JNI
891:     _attaching_via_jni,          // thread is attaching via JNI
892:     _attached_via_jni            // thread has attached via JNI
896:   // A native thread that is attaching via JNI starts with a value
901:   // State of the stack guard pages for this thread.
957:   ObjPtrQueue _satb_mark_queue;          // Thread-local log for SATB barrier.
961:   DirtyCardQueue _dirty_card_queue;      // Thread-local log for dirty cards.
976:   JavaThread(bool is_attaching_via_jni = false); // for main thread and JNI attached threads
993:   // This function is called at thread creation to allow
994:   // platform specific thread variables to be initialized.
1000:   // Cleanup on thread exit
1007:   void cleanup_failed_attach_current_thread();
1012:   // Thread chain operations
1016:   // Thread oop. threadObj() can be NULL for initial JavaThread
1023:   // Prepare thread and add to priority queue.  If a priority is
1024:   // not specified, use the priority of the thread object. Threads_lock
1026:   void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
1035:   // Allocates a new Java level thread object for this thread. thread_name may be NULL.
1036:   void allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS);
1055:   // Use membars when accessing volatile _thread_state. See
1057:   inline JavaThreadState thread_state() const;
1058:   inline void set_thread_state(JavaThreadState s);
1064:   // thread has called JavaThread::exit() or is terminated
1065:   bool is_exiting()                              { return _terminated == _thread_exiting || is_terminated(); }
1066:   // thread is terminated (no longer on the threads list); we compare
1069: ...(8 bytes skipped)...s_terminated()                           { return _terminated != _not_terminated && _terminated != _thread_exiting; }
1072:   void set_terminated_value()                    { _terminated = _thread_terminated; }
1099:         // don't surprise the thread that suspended us by returning
1105:   static void check_safepoint_and_suspend_for_native_trans(JavaThread *thread);
1107:   static void check_special_condition_for_native_trans(JavaThread *thread);
1110:   // transition into thread_in_Java mode so that it can potentially
1112:   static void check_special_condition_for_native_trans_and_transition(JavaThread *thread);
1118:     // SR_lock to allow the thread to reach a stable thread state if
1119:     // it is currently in a transient thread state.
1142:   // Whenever a thread transitions from native to vm/java it must suspend
1189:   // Thread.stop support
1190:   void send_thread_stop(oop throwable);
1317:   // Returns true if (a) guard pages are not needed on this thread, (b) the
1384:   // Returns the jni environment for this thread
1388:     JavaThread *thread_from_jni_env = (JavaThread*)((intptr_t)env - in_bytes(jni_environment_offset()));
1389:     // Only return NULL if thread is off the thread list; starting to
1391:     if (thread_from_jni_env->is_terminated()) {
1392:        thread_from_jni_env->block_if_vm_exited();
1395:        return thread_from_jni_env;
1402:   void enter_critical() { assert(Thread::current() == this ||
1403:                                  Thread::current()->is_VM_thread() && SafepointSynchronize::is_synchronizing(),
1404:                                  "this must be current thread or synchronizing");
1406:   void exit_critical()  { assert(Thread::current() == this,
1407:                                  "this must be current thread");
1460:   char* name() const { return (char*)get_thread_name(); }
1464:   void print_thread_state_on(outputStream* ) const      PRODUCT_RETURN;
1465:   void print_thread_state() const                       PRODUCT_RETURN;
1468:   const char* get_thread_name() const;
1471:   const char* get_thread_name_string(char* buf = NULL, int buflen = 0) const;
1519:    friend class FlatProfiler;                    // uses both [gs]et_thread_profiler.
1520:    friend class FlatProfilerTask;                // uses get_thread_profiler.
1521:    friend class ThreadProfilerMark;              // uses get_thread_profiler.
1524:      ThreadProfiler* result = _thread_profiler;
1525:      _thread_profiler = tp;
1530:   // Returns the running thread as a JavaThread
1533:   // Returns the active Java thread.  Do not use this if you know you are calling
1543:   void thread_main_inner();
1557:   // Thread local information maintained by JVMTI.
1559:   // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1638:   // support for cached flag that indicates whether exceptions need to be posted for this thread
1654:   // Return a blocker object for which this thread is blocked parking.
1683:   // JavaThread is added to the Java thread list. Right now, we don't
1685:   // activated when the thread was created), but we have to activate
1686:   // the SATB queue if the thread is created while a marking cycle is
1691:   // now, it is called just before the thread is added to the Java
1692:   // thread list in the Threads::add() method. That method is holding
1695:   // when the thread is created given that, in some cases, safepoints
1697:   // thread being added to the Java thread list (an example of this is
1698:   // when the structure for the DestroyJavaVM thread is created).
1707: # include "thread_linux_x86.hpp"
1710: # include "thread_linux_sparc.hpp"
1713: # include "thread_linux_zero.hpp"
1716: # include "thread_solaris_x86.hpp"
1719: # include "thread_solaris_sparc.hpp"
1722: # include "thread_windows_x86.hpp"
1725: # include "thread_linux_arm.hpp"
1728: # include "thread_linux_ppc.hpp"
1731: # include "thread_aix_ppc.hpp"
1734: # include "thread_bsd_x86.hpp"
1737: # include "thread_bsd_zero.hpp"
1753:   // JSR166 per-thread parker
1771:   // This field is used to determine if a thread has claimed
1772:   // a par_id: it is UINT_MAX if the thread has not claimed a par_id;
1782:   Thread* thread = ThreadLocalStorage::thread();
1783:   assert(thread != NULL && thread->is_Java_thread(), "just checking");
1784:   return (JavaThread*)thread;
1788:   assert(is_Compiler_thread(), "just checking");
1803:       !(DisablePrimordialThreadGuardPages && os::is_primordial_thread())) {
1821: // A thread used for Compilation.
1843:   // Hide this compiler thread from external view.
1852:   // Get/set the thread's compilation environment.
1859:   // Get/set the thread's logging information
1880:   // Get/set the thread's current task
1896: // The active thread queue. It also keeps track of the current used
1897: // thread priorities.
1910:   // Thread management
1912:   // thread to the thread list before allocating its thread object
1916:   static JavaThread* first()                     { return _thread_list; }
1919:   // Initializes the vm and creates the vm thread
1940:   // This creates a list of GCTasks, one per thread.
1941:   static void create_thread_roots_tasks(GCTaskQueue* q);
1942:   // This creates a list of GCTasks, one per thread, for marking objects.
1943:   static void create_thread_roots_marking_tasks(GCTaskQueue* q);
1971:   static void print_on_error(outputStream* st, Thread* current, char* buf, int buflen);
1979:   // Get owning Java thread from the monitor's owner field. If doLock
1982:   static JavaThread *owning_thread_from_monitor_owner(address owner,
1993:   static JavaThread* find_java_thread_from_java_tid(jlong java_tid);
1998: // Thread iterator
2001:   virtual void do_thread(Thread* thread) = 0;
2008:   SignalHandlerMark(Thread* t) {
2009:     _thread = t;
2010:     if (_thread) _thread->enter_signal_handler();
2013:     if (_thread) _thread->leave_signal_handler();
2014:     _thread = NULL;
2019: #endif // SHARE_VM_RUNTIME_THREAD_HPP
29: #include "memory/threadLocalAllocBuffer.hpp"
38: #include "runtime/osThread.hpp"
42: #include "runtime/threadLocalStorage.hpp"
58: class ThreadSafepointState;
59: class ThreadProfiler;
63: class ThreadStatistics;
69: class CompileThread;
80: class ThreadClosure;
89: class WorkerThread;
93: //   - NamedThread
94: //     - VMThread
95: //     - ConcurrentGCThread
96: //     - WorkerThread
98: //       - GCTaskThread
99: //   - JavaThread
100: //   - WatcherThread
106:   // (Note: _pending_exception and friends are in ThreadShadow)
120:    static void* allocate(size_t size, bool throw_excpt, MEMFLAGS flags = mtThread);
133:   // External suspend/resume requests come from JVM_SuspendThread,
134:   // JVM_ResumeThread, JVMTI SuspendThread, and finally JVMTI
135:   // ResumeThread. External
140:   // for already suspended threads.
147:   // condition lifts, the JavaThread will self-suspend. Other places
160:   // the interface that requires quiescence, we give the JavaThread a
175:   // 1. The suspend/resume logic no longer uses ThreadState in OSThread
177:   // JVMTI) happy. ThreadState is legacy code (see notes in
178:   // osThread.hpp).
253:   friend class ThreadLocalStorage;
265:   ThreadExt _ext;
317:   // threads.
432:   ThreadLocalAllocBuffer& tlab()                 { return _tlab; }
446:   const ThreadExt& ext() const          { return _ext; }
447:   ThreadExt& ext()                      { return _ext; }
479:   //   Used by JavaThread::oops_do.
490:   // uses an atomic instruction to set the current threads parity to
521:   // creation fails due to lack of memory, too many threads etc.
680: // Name support for threads.  non-JavaThread subclasses with multiple
689:   // log JavaThread being processed by oops_do
693:   NamedThread();
694:   ~NamedThread();
703: // Worker threads are named and have an id of an assigned work.
713:     return (WorkerThread*) this;
720: // A single WatcherThread is used for simulating timer interrupts.
739:   WatcherThread();
750:   // Returns the single instance of WatcherThread
753:   // Create and start the single instance of WatcherThread, or stop it on shutdown
773: class CompilerThread;
807:   ThreadFunction _entry_point;
864:   // JavaThread termination support
869:     _vm_exited                                   // JavaThread is still executing native code, but VM is terminated
873:   // In general a JavaThread's _terminated field transitions as follows:
877:   // _vm_exited is a special value to cover the case of a JavaThread
895:   // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni.
968:   friend class VMThread;
969:   friend class ThreadWaitTransition;
977:   JavaThread(ThreadFunction entry_point, size_t stack_size = 0);
978:   ~JavaThread();
981:   // verify this JavaThread hasn't be published in the Threads::list yet
1013:   JavaThread* next() const                       { return _next; }
1014:   void set_next(JavaThread* p)                   { _next = p; }
1017:   // (or for threads attached via JNI)
1021:   ThreadPriority java_priority() const;          // Read from threadObj()
1033:   ThreadFunction entry_point() const             { return _entry_point; }
1056:   // Threads::create_vm() for size checks.
1060:   ThreadSafepointState *safepoint_state() const  { return _safepoint_state; }
1061:   void set_safepoint_state(ThreadSafepointState *state) { _safepoint_state = state; }
1067:   // against the two non-terminated values so that a freed JavaThread
1071:   // special for Threads::remove() which is static:
1081:   // Suspend/resume support for JavaThread
1092:     assert(JavaThread::current() == this, "sanity check");
1205:   // Return true if JavaThread has an asynchronous condition or
1347:   static ByteSize jmp_ring_index_offset()        { return byte_offset_of(JavaThread, _jmp_ring_index      ); }
1348:   static ByteSize jmp_ring_offset()              { return byte_offset_of(JavaThread, _jmp_ring            ); }
1350:   static ByteSize jni_environment_offset()       { return byte_offset_of(JavaThread, _jni_environment     ); }
1352:     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
1355:     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
1358:     return byte_offset_of(JavaThread, _anchor);
1360:   static ByteSize callee_target_offset()         { return byte_offset_of(JavaThread, _callee_target       ); }
1361:   static ByteSize vm_result_offset()             { return byte_offset_of(JavaThread, _vm_result           ); }
1362:   static ByteSize vm_result_2_offset()           { return byte_offset_of(JavaThread, _vm_result_2         ); }
1364:   static ByteSize saved_exception_pc_offset()    { return byte_offset_of(JavaThread, _saved_exception_pc  ); }
1366:   static ByteSize exception_oop_offset()         { return byte_offset_of(JavaThread, _exception_oop       ); }
1367:   static ByteSize exception_pc_offset()          { return byte_offset_of(JavaThread, _exception_pc        ); }
1368:   static ByteSize exception_handler_pc_offset()  { return byte_offset_of(JavaThread, _exception_handler_pc); }
1369:   static ByteSize stack_overflow_limit_offset()  { return byte_offset_of(JavaThread, _stack_overflow_limit); }
1370:   static ByteSize is_method_handle_return_offset() { return byte_offset_of(JavaThread, _is_method_handle_return); }
1371:   static ByteSize stack_guard_state_offset()     { return byte_offset_of(JavaThread, _stack_guard_state   ); }
1372:   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags       ); }
1374:   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
1376:     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
1380:   static ByteSize satb_mark_queue_offset()       { return byte_offset_of(JavaThread, _satb_mark_queue); }
1381:   static ByteSize dirty_card_queue_offset()      { return byte_offset_of(JavaThread, _dirty_card_queue); }
1439:   void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; }
1473:   const char* get_threadgroup_name() const;
1531:   static inline JavaThread* current();
1534:   // from a JavaThread, as it's slower than JavaThread::current.  If called from
1535:   // the VMThread, it also returns the JavaThread that instigated the VMThread's
1537:   static JavaThread* active();
1539:   inline CompilerThread* as_CompilerThread();
1560:   // getter is used to get this JavaThread's JvmtiThreadState if it has
1562:   // is used to get the specified JavaThread's JvmtiThreadState if it has
1563:   // one or it allocates a new JvmtiThreadState for the JavaThread and
1565:   // the specified JavaThread is exiting.
1589:   static ByteSize popframe_condition_offset()         { return byte_offset_of(JavaThread, _popframe_condition); }
1632:   static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
1693:   // the Threads_lock which ensures we are outside a safepoint. We
1696:   // might happen between the JavaThread constructor being called and the
1780: // Inline implementation of JavaThread::current
1781: inline JavaThread* JavaThread::current() {
1789:   return (CompilerThread*)this;
1792: inline bool JavaThread::stack_guard_zone_unused() {
1796: inline bool JavaThread::stack_yellow_zone_disabled() {
1800: inline bool JavaThread::stack_yellow_zone_enabled() {
1810: inline size_t JavaThread::stack_available(address cur_sp) {
1838:   static CompilerThread* current();
1840:   CompilerThread(CompileQueue* queue, CompilerCounters* counters);
1891: inline CompilerThread* CompilerThread::current() {
1892:   return JavaThread::current()->as_CompilerThread();
1913:   static void add(JavaThread* p, bool force_daemon = false);
1914:   static void remove(JavaThread* p);
1915:   static bool includes(JavaThread* p);
1917:   static void threads_do(ThreadClosure* tc);
1935:   // Apply "f->do_oop" to all root oops in all threads.
1945:   // Apply "f->do_oop" to roots in all threads that
1973:   // Get Java threads that are waiting to enter a monitor. If doLock
1974:   // is true, then Threads_lock is grabbed as needed. Otherwise, the
1976:   static GrowableArray<JavaThread*>* get_pending_threads(int count,
1980:   // is true, then Threads_lock is grabbed as needed. Otherwise, the
1985:   // Number of threads on the active threads list
1987:   // Number of non-daemon threads on the active threads list
61: class JvmtiThreadState;
732:   os::WatcherThreadCrashProtection* _crash_protection;
760:   void set_crash_protection(os::WatcherThreadCrashProtection* crash_protection) {
766:   os::WatcherThreadCrashProtection* crash_protection() const { return _crash_protection; }
1561:   // one which means NULL can be returned. JvmtiThreadState::state_for()
1564:   // returns it. JvmtiThreadState::state_for() will return NULL only if
chromium.googlesource.com/arc/arc:third_party/chromium-ppapi/native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ master, ] Duplicate result
chromium.googlesource.com/chromium/chromium:native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ trunk, ] Duplicate result
chromium.googlesource.com/dart/dartium/src:native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ master, ] Duplicate result
chromium.googlesource.com/chromium:native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ trunk, ] Duplicate result
chromium.googlesource.com/git/chromium:native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ trunk, ] Duplicate result
android.googlesource.com/platform/libcore2:luni/src/main/java/java/util/concurrent/ThreadPoolExecutor.java: [ master, ]
556:         final Thread thread;
285: public class ThreadPoolExecutor extends AbstractExecutorService {
469:     private volatile ThreadFactory threadFactory;
1128:     public ThreadPoolExecutor(int corePoolSize,
1162:     public ThreadPoolExecutor(int corePoolSize,
1197:     public ThreadPoolExecutor(int corePoolSize,
1234:     public ThreadPoolExecutor(int corePoolSize,
1509:     public boolean prestartCoreThread() {
489:     private volatile boolean allowCoreThreadTimeOut;
1421:     public void setThreadFactory(ThreadFactory threadFactory) {
1433:     public ThreadFactory getThreadFactory() {
1533:     public int prestartAllCoreThreads() {
1553:     public boolean allowsCoreThreadTimeOut() {
1574:     public void allowCoreThreadTimeOut(boolean value) {
21:  * <p>Thread pools address two different problems: they usually
33:  * Executors#newCachedThreadPool} (unbounded thread pool, with
34:  * automatic thread reclamation), {@link Executors#newFixedThreadPool}
35:  * (fixed size thread pool) and {@link
36:  * Executors#newSingleThreadExecutor} (single background thread), that
52:  * than corePoolSize threads are running, a new thread is created to
55:  * threads running, a new thread will be created only if the queue is
57:  * create a fixed-size thread pool. By setting maximumPoolSize to an
79:  * alter the thread's name, thread group, priority, daemon status,
80:  * etc. If a {@code ThreadFactory} fails to create a thread when asked
109:  * always prefers adding a new thread
114:  * thread.</li>
116:  * <li> If a request cannot be queued, a new thread is created unless
129:  * new thread will be constructed. This policy avoids lockups when
133:  * possibility of unbounded thread growth when commands continue to
183:  * <li> In {@link ThreadPoolExecutor.CallerRunsPolicy}, the thread
250:  *   protected void beforeExecute(Thread t, Runnable r) {
302:      * for example when a ThreadFactory fails to create a thread when
314:      *             the thread transitioning to state TIDYING
392:      * abrupt termination of a thread (see processWorkerExit). Other
514:      * (as governed by Thread.interrupt, which relies on
519:      * All actual invocations of Thread.interrupt (see
524:      * allowing access to a thread and sometimes not. In such cases,
539:      * intended to wake up a worker thread waiting for a task from
555:         /** Thread this worker is running in.  Null if factory fails. */
559:         /** Per-thread task counter */
563:          * Creates with given first task and thread from ThreadFactory.
568:             this.thread = getThreadFactory().newThread(this);
587:                 setExclusiveOwnerThread(Thread.currentThread());
674:      * to interrupt each worker thread. This might not be true even if
686:                     security.checkAccess(w.thread);
703:                     w.thread.interrupt();
724:      * Interrupting any arbitrary thread ensures that newly arriving
736:                 Thread t = w.thread;
764:      * Ensures that unless the pool is stopping, the current thread
771:             Thread.interrupted() &&
773:             Thread.currentThread().interrupt();
837:      * eligible to shut down. It also returns false if the thread
838:      * factory fails to create a thread when asked, which requires a
842:      * @param firstTask the task the new thread should run first (or
884:         Thread t = w.thread;
914:         // It is possible (but unlikely) for a thread to have been
917:         // because Thread.interrupt is not guaranteed to have any effect
918:         // on a non-yet-started Thread (see Thread#interrupt).
929:      * for exit.  This method removes thread from worker set, and
1035:      * usually leads processWorkerExit to replace this thread.
1040:      * stopping, this thread does not have its interrupt set.
1043:      * might throw an exception, in which case we cause thread to die
1053:      * thread's UncaughtExceptionHandler).  Any thrown exception also
1054:      * conservatively causes thread to die.
1057:      * also throw an exception, which will also cause thread to
1062:      * and the thread's UncaughtExceptionHandler have as accurate
1077:                     beforeExecute(w.thread, task);
1106:      * parameters and default thread factory and rejected execution handler.
1153:      *        creates a new thread
1174:      * parameters and default thread factory.
1188:      *        because the thread bounds and queue capacities are reached
1223:      *        creates a new thread
1225:      *        because the thread bounds and queue capacities are reached
1258:      * may execute in a new thread or in an existing pooled thread.
1277:          * start a new thread with the given command as its first
1283:          * to double-check whether we should have added a thread
1287:          * stopped, or start a new thread if there are none.
1290:          * thread.  If it fails, we know we are shut down or saturated
1345:      * cancels tasks via {@link Thread#interrupt}, so any task that
1415:      * Sets the thread factory used to create new threads.
1417:      * @param threadFactory the new thread factory
1428:      * Returns the thread factory used to create new threads.
1430:      * @return the current thread factory
1502:      * Starts a core thread, causing it to idly wait for work. This
1507:      * @return {@code true} if a thread was started
1516:      * thread is started even if corePoolSize is 0.
1564:      * continual thread replacement, the keep-alive time must be
1641:      * Returns the thread keep-alive time, which is the amount of time
1863:      * given thread.  This method is invoked by thread {@code t} that
1872:      * @param t the thread that will run task {@code r}
1875:     protected void beforeExecute(Thread t, Runnable r) { }
1879:      * This method is invoked by the thread that executed the task. If
1911:      *           Thread.currentThread().interrupt(); // ignore/reset
1937:      * directly in the calling thread of the {@code execute} method,
1948:          * Executes task r in the caller's thread, unless the executor
18:  * one of possibly several pooled threads, normally configured
25:  * including threads, consumed when executing a collection of tasks.
26:  * Each {@code ThreadPoolExecutor} also maintains some basic
45:  * <dd>A {@code ThreadPoolExecutor} will automatically adjust the
53:  * handle the request, even if other worker threads are idle.  If
66:  * <dd> By default, even core threads are initially created and
68:  * dynamically using method {@link #prestartCoreThread} or {@link
69:  * #prestartAllCoreThreads}.  You probably want to prestart threads if
72:  * <dt>Creating new threads</dt>
74:  * <dd>New threads are created using a {@link ThreadFactory}.  If not
76:  * used, that creates threads to all be in the same {@link
77:  * ThreadGroup} and with the same {@code NORM_PRIORITY} priority and
78:  * non-daemon status. By supplying a different ThreadFactory, you can
81:  * by returning null from {@code newThread}, the executor will
86:  * <dd>If the pool currently has more than corePoolSize threads,
87:  * excess threads will be terminated if they have been idle for more
91:  * threads will be constructed. This parameter can also be changed
94:  * disables idle threads from ever terminating prior to shut down. By
98:  * time-out policy to core threads as well, so long as the
108:  * <li> If fewer than corePoolSize threads are running, the Executor
112:  * <li> If corePoolSize or more threads are running, the Executor
126:  * queue is a {@link SynchronousQueue} that hands off tasks to threads
128:  * will fail if no threads are immediately available to run it, so a
139:  * corePoolSize threads are busy. Thus, no more than corePoolSize
140:  * threads will ever be created. (And the value of the maximumPoolSize
157:  * time for more threads than you otherwise allow. Use of small queues
170:  * when the Executor uses finite bounds for both maximum threads and
179:  * <li> In the default {@link ThreadPoolExecutor.AbortPolicy}, the
188:  * <li> In {@link ThreadPoolExecutor.DiscardPolicy}, a task that
191:  * <li>In {@link ThreadPoolExecutor.DiscardOldestPolicy}, if the
209:  * ThreadLocals, gathering statistics, or adding log
215:  * threads may in turn fail and abruptly terminate.</dd>
229:  * has no remaining threads will be {@code shutdown} automatically. If
232:  * that unused threads eventually die, by setting appropriate
233:  * keep-alive times, using a lower bound of zero core threads and/or
243:  * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
289:      *   workerCount, indicating the effective number of threads
293:      * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
301:      * transiently different from the actual number of live threads,
303:      * asked, and when exiting threads are still performing
333:      * Threads waiting in awaitTermination() will return when the
401:      * threads.  We do not require that workQueue.poll() returning
418:      * Otherwise exiting threads would concurrently interrupt those
428:      * Set containing all worker threads in pool. Accessed only when
446:      * worker threads. Accessed only under mainLock.
458:      * Factory for new threads. All threads are created using this
461:      * policy limiting the number of threads.  Even though it is not
462:      * treated as an error, failure to create threads may result in
466:      * create threads, since there is generally no recourse from
477:      * Timeout in nanoseconds for idle threads waiting for work.
478:      * Threads use this timeout when there are more than corePoolSize
485:      * If false (default), core threads stay alive even when idle.
486:      * If true, core threads use keepAliveTime to time out waiting
513:      * have permission to actually interrupt threads in the worker set
515:      * ThreadGroup.checkAccess, which in turn relies on
525:      * failure to actually interrupt threads may disable or delay full
531:         new RuntimePermission("modifyThread");
535:      * threads running tasks, along with other minor bookkeeping.
594:             setExclusiveOwnerThread(null);
667:      * Methods for controlling interrupts to worker threads.
672:      * permission to shut down threads in general (see shutdownPerm).
675:      * first check passed, if the SecurityManager treats some threads
694:      * Interrupts all threads, even if active. Ignores SecurityExceptions
695:      * (in which case some threads may remain uninterrupted).
713:      * Interrupts threads that might be waiting for tasks (as
716:      * SecurityExceptions (in which case some threads may remain
723:      * signals in case all threads are currently waiting.
845:      * than corePoolSize threads (in which case we always start one),
847:      * Initially idle threads are usually created via
848:      * prestartCoreThread or to replace other dying workers.
890:             // Back out on ThreadFactory failure or if
927:      * only from worker threads. Unless completedAbruptly is set,
1105:      * Creates a new {@code ThreadPoolExecutor} with the given initial
1110:      * @param corePoolSize the number of threads to keep in the pool, even
1112:      * @param maximumPoolSize the maximum number of threads to allow in the
1114:      * @param keepAliveTime when the number of threads is greater than
1115:      *        the core, this is the maximum time that excess idle threads
1138:      * Creates a new {@code ThreadPoolExecutor} with the given initial
1141:      * @param corePoolSize the number of threads to keep in the pool, even
1143:      * @param maximumPoolSize the maximum number of threads to allow in the
1145:      * @param keepAliveTime when the number of threads is greater than
1146:      *        the core, this is the maximum time that excess idle threads
1152:      * @param threadFactory the factory to use when the executor
1160:      *         or {@code threadFactory} is null
1167:                               ThreadFactory threadFactory) {
1169:              threadFactory, defaultHandler);
1173:      * Creates a new {@code ThreadPoolExecutor} with the given initial
1176:      * @param corePoolSize the number of threads to keep in the pool, even
1178:      * @param maximumPoolSize the maximum number of threads to allow in the
1180:      * @param keepAliveTime when the number of threads is greater than
1181:      *        the core, this is the maximum time that excess idle threads
1208:      * Creates a new {@code ThreadPoolExecutor} with the given initial
1211:      * @param corePoolSize the number of threads to keep in the pool, even
1213:      * @param maximumPoolSize the maximum number of threads to allow in the
1215:      * @param keepAliveTime when the number of threads is greater than
1216:      *        the core, this is the maximum time that excess idle threads
1222:      * @param threadFactory the factory to use when the executor
1232:      *         or {@code threadFactory} or {@code handler} is null
1239:                               ThreadFactory threadFactory,
1246:         if (workQueue == null || threadFactory == null || handler == null)
1252:         this.threadFactory = threadFactory;
1276:          * 1. If fewer than corePoolSize threads are running, try to
1280:          * threads when it shouldn't, by returning false.
1408:      * referenced and it has no threads.
1418:      * @throws NullPointerException if threadFactory is null
1422:         if (threadFactory == null)
1424:         this.threadFactory = threadFactory;
1434:         return threadFactory;
1461:      * Sets the core number of threads.  This overrides any value set
1463:      * current value, excess existing threads will be terminated when
1464:      * they next become idle.  If larger, new threads will, if needed,
1479:             // We don't really know how many new threads are "needed".
1492:      * Returns the core number of threads.
1494:      * @return the core number of threads
1503:      * overrides the default policy of starting core threads only when
1505:      * if all core threads have already been started.
1515:      * Same as prestartCoreThread except arranges that at least one
1527:      * Starts all core threads, causing them to idly wait for work. This
1528:      * overrides the default policy of starting core threads only when
1531:      * @return the number of threads started
1541:      * Returns true if this pool allows core threads to time out and
1544:      * keep-alive policy applying to non-core threads applies also to
1545:      * core threads. When false (the default), core threads are never
1548:      * @return {@code true} if core threads are allowed to time out,
1558:      * Sets the policy governing whether core threads may time out and
1561:      * threads are never terminated due to lack of incoming
1563:      * non-core threads applies also to core threads. To avoid
1576:             throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1585:      * Sets the maximum allowed number of threads. This overrides any
1587:      * the current value, excess existing threads will be
1605:      * Returns the maximum allowed number of threads.
1607:      * @return the maximum allowed number of threads
1615:      * Sets the time limit for which threads may remain idle before
1617:      * threads currently in the pool, after waiting this amount of
1618:      * time without processing a task, excess threads will be
1622:      *        excess threads to terminate immediately after executing tasks.
1632:             throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1642:      * that threads in excess of the core pool size may remain
1694:      * accumulate in work queues until worker threads can actively
1697:      * the presence of interference by other threads.
1723:      * Returns the current number of threads in the pool.
1725:      * @return the number of threads
1741:      * Returns the approximate number of threads that are actively
1744:      * @return the number of threads
1761:      * Returns the largest number of threads that have ever
1764:      * @return the number of threads
1779:      * threads may change dynamically during computation, the returned
1802:      * completed execution. Because the states of tasks and threads
1853:             ", active threads = " + nactive +
1865:      * ThreadLocals, or to perform logging.
1899:      * class ExtendedExecutor extends ThreadPoolExecutor {
1954:         public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1978:         public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
2001:         public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
2025:         public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
75:  * otherwise specified, a {@link Executors#defaultThreadFactory} is
96:  * than corePoolSizeThreads. But method {@link
97:  * #allowCoreThreadTimeOut(boolean)} can be used to apply this
234:  * setting {@link #allowCoreThreadTimeOut(boolean)}.  </dd>
248:  *   public PausableThreadPoolExecutor(...) { super(...); }
479:      * present or if allowCoreThreadTimeOut. Otherwise they wait
493:      * (and not allow to time out etc) unless allowCoreThreadTimeOut
633:      * allow access from ScheduledThreadPoolExecutor.
778:      * ScheduledThreadPoolExecutor
783:      * Package-protected for use by ScheduledThreadPoolExecutor.
792:      * ScheduledThreadPoolExecutor to cancel delayed tasks.
798:      * State check needed by ScheduledThreadPoolExecutor to
956:                 int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
976:      *    {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
1000:                 timed = allowCoreThreadTimeOut || wc > corePoolSize;
1111:      *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
1134:              Executors.defaultThreadFactory(), defaultHandler);
1142:      *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
1177:      *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
1204:              Executors.defaultThreadFactory(), handler);
1212:      *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
1326:             onShutdown(); // hook for ScheduledThreadPoolExecutor
1419:      * @see #getThreadFactory
1431:      * @see #setThreadFactory
1554:         return allowCoreThreadTimeOut;
1577:         if (value != allowCoreThreadTimeOut) {
1578:             allowCoreThreadTimeOut = value;
1625:      *         if {@code time} is zero and {@code allowsCoreThreadTimeOut}
1631:         if (time == 0 && allowsCoreThreadTimeOut())
android.googlesource.com/platform/libcore:ojluni/annotations/hiddenapi/java/lang/Thread.java: [ master, ]
32: public class Thread implements java.lang.Runnable {
34:     public Thread() {
38:     public Thread(java.lang.Runnable target) {
42:     Thread(java.lang.Runnable target, java.security.AccessControlContext acc) {
46:     public Thread(java.lang.ThreadGroup group, java.lang.Runnable target) {
50:     public Thread(java.lang.String name) {
54:     public Thread(java.lang.ThreadGroup group, java.lang.String name) {
59:     Thread(java.lang.ThreadGroup group, java.lang.String name, int priority, boolean daemon) {
63:     public Thread(java.lang.Runnable target, java.lang.String name) {
67:     public Thread(java.lang.ThreadGroup group, java.lang.Runnable target, java.lang.String name) {
71:     public Thread(
91:     public static native java.lang.Thread currentThread();
424:     private static int threadInitNumber;
426:     int threadLocalRandomProbe;
428:     int threadLocalRandomSecondarySeed;
430:     long threadLocalRandomSeed;
435:     java.lang.ThreadLocal.ThreadLocalMap threadLocals;
437:     private java.lang.Thread threadQ;
440:     private static long threadSeqNumber;
79:     private static synchronized int nextThreadNum() {
83:     private static synchronized long nextThreadID() {
198:     public final java.lang.ThreadGroup getThreadGroup() {
385:     java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals;
127:     private void init2(java.lang.Thread parent) {
135:     private static native void nativeCreate(java.lang.Thread t, long stackSize, boolean daemon);
206:     public static int enumerate(java.lang.Thread[] tarray) {
261:     public static java.util.Map<java.lang.Thread, java.lang.StackTraceElement[]>
278:     public java.lang.Thread.State getState() {
283:             java.lang.Thread.UncaughtExceptionHandler eh) {
287:     public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() {
292:             java.lang.Thread.UncaughtExceptionHandler eh) {
297:     public static java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionPreHandler() {
301:     public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
305:     public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler eh) {
376:     private static volatile java.lang.Thread.UncaughtExceptionHandler
444:     private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
447:     private static volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionPreHandler;
457:                         java.lang.Thread.WeakClassKey, java.lang.Boolean>
502:         public void uncaughtException(java.lang.Thread t, java.lang.Throwable e);
72:             java.lang.ThreadGroup group,
107:             java.lang.ThreadGroup g,
115:             java.lang.ThreadGroup g,
382:     private java.lang.ThreadGroup group;
github.com/google/grumpy:third_party/stdlib/threading.py: [ master, ]
631: class Thread(_Verbose):
35: _start_new_thread = thread.start_new_thread
1148: current_thread = currentThread
38: ThreadError = thread.error
1071: class _MainThread(Thread):
1096: def _pickSomeNonDaemonThread():
1111: class _DummyThread(Thread):
1135: def currentThread():
1365:     class ProducerThread(Thread):
1381:     class ConsumerThread(Thread):
1: """Thread module emulating a subset of Java's threading model."""
6:     import thread
31:            'current_thread', 'enumerate', 'Event',
32:            'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
36: _allocate_lock = thread.allocate_lock
37: _get_ident = thread.get_ident
39: del thread
67:                 # Issue #4188: calling current_thread() can incur an infinite
73:                     name = "<OS thread %d>" % ident
93:     The func will be passed to sys.setprofile() for each thread, before its
103:     The func will be passed to sys.settrace() for each thread, before its run()
117:     A reentrant lock must be released by the thread that acquired it. Once a
118:     thread has acquired a reentrant lock, the same thread may acquire it again
119:     without blocking; the thread must release it once for each time it has
126:     """A reentrant lock must be released by the thread that acquired it. Once a
127:        thread has acquired a reentrant lock, the same thread may acquire it
128:        again without blocking; the thread must release it once for each time it
150:         When invoked without arguments: if this thread already owns the lock,
152:         if another thread owns the lock, block until the lock is unlocked. Once
153:         the lock is unlocked (not owned by any thread), then grab ownership, set
154:         the recursion level to one, and return. If more than one thread is
191:         by any thread), and if any other threads are blocked waiting for the
194:         locked and owned by the calling thread.
196:         Only call this method when the calling thread owns the lock. A
246:     notified by another thread.
257:        notified by another thread.
301:         # Return True if lock is owned by current_thread.
312:         If the calling thread has not acquired the lock when this method is
317:         variable in another thread, or until the optional timeout occurs. Once
376:         If the calling thread has not acquired the lock when this method is
403:         If the calling thread has not acquired the lock when this method
445:         on entry, block, waiting until some other thread has called release() to
482:         When the counter is zero on entry and another thread is waiting for it
483:         to become larger than zero again, wake up that thread.
528:         When the counter is zero on entry and another thread is waiting for it
529:         to become larger than zero again, wake up that thread.
567:         # private!  called by Thread._reset_internal_locks by _after_fork()
601:         block until another thread calls set() to set the flag to true, or until
617: # Helper to generate new thread names
619: _counter() # Consume 0 so first non-main thread has id 1.
620: def _newname(template="Thread-%d"):
623: # Active thread administration
625: _active = {}    # maps thread id to Thread object
632:     """A class that represents a thread of control.
649:         *name* is the thread name. By default, a unique name is constructed of
650:         the form "Thread-N" where N is a small decimal number.
658:         the base class constructor (Thread.__init__()) before doing anything
659:         else to the thread.
694:         return current_thread().daemon
697:         assert self.__initialized, "Thread.__init__() was not called"
710:         """Start the thread's activity.
712:         It must be called at most once per thread object. It arranges for the
713:         object's run() method to be invoked in a separate thread of control.
716:         same thread object.
720:             raise RuntimeError("thread.__init__() not called")
724:             self._note("%s.start(): starting thread", self)
728:             _start_new_thread(self.__bootstrap, ())
736:         """Method representing the thread's activity.
748:             # Avoid a refcycle if the thread is running a function with
749:             # an argument that has a member that points to the thread.
755:         # happen when a daemon thread wakes up at an unfortunate
783:                 self._note("%s.__bootstrap(): thread started", self)
805:                     print>>_sys.stderr, ("Exception in thread %s:\n%s" %
814:                             "Exception in thread " + self.name +
860:         "Remove current thread from the dict of currently running threads."
862:         # Notes about running with dummy_thread:
864:         # Must take care to not raise an exception if dummy_thread is being
866:         # dummy_threading).  dummy_thread.get_ident() always returns -1 since
867:         # there is only one thread if dummy_thread is being used.  Thus
868:         # len(_active) is always <= 1 here, and any Thread instance created
869:         # overwrites the (if any) thread currently registered in _active.
872:         # gets overwritten the instant an instance of Thread is created; both
873:         # threads return -1 from dummy_thread.get_ident() and thus have the
876:         # it gets a KeyError if another Thread instance was created.
888:                 # could try to acquire the lock again in the same thread, (in
889:                 # current_thread()), and would block.
895:         """Wait until the thread terminates.
897:         This blocks the calling thread until the thread whose join() method is
905:         thread is still alive, the join() call timed out.
908:         block until the thread terminates.
910:         A thread can be join()ed many times.
913:         thread as that would cause a deadlock. It is also an error to join() a
914:         thread before it has been started and attempts to do so raises the same
919:             raise RuntimeError("Thread.__init__() not called")
921:             raise RuntimeError("cannot join thread before it is started")
922:         if self is current_thread():
923:             raise RuntimeError("cannot join current thread")
927:                 self._note("%s.join(): waiting until thread stops", self)
934:                     self._note("%s.join(): thread stopped", self)
946:                         self._note("%s.join(): thread stopped", self)
957:         assert self.__initialized, "Thread.__init__() not called"
961:         assert self.__initialized, "Thread.__init__() not called"
968:         """Thread identifier of this thread or None if it has not been started.
970:         This is a nonzero integer. See the thread.get_ident() function. Thread
971:         identifiers may be recycled when a thread exits and another thread is
972:         created. The identifier is available even after the thread has exited.
975:         assert self.__initialized, "Thread.__init__() not called"
979:         """Return whether the thread is alive.
986:         assert self.__initialized, "Thread.__init__() not called"
992:         """A boolean value indicating whether this thread is a daemon thread (True) or not (False).
995:         raised. Its initial value is inherited from the creating thread; the
996:         main thread is not a daemon thread and therefore all threads created in
997:         the main thread default to daemon = False.
1003:         assert self.__initialized, "Thread.__init__() not called"
1008:             raise RuntimeError("Thread.__init__() not called")
1010:             raise RuntimeError("cannot set daemon status of active thread");
1041: class _Timer(Thread):
1051:         Thread.__init__(self)
1068: # Special thread class to represent the main thread
1074:         Thread.__init__(self, name="MainThread")
1103: # Dummy thread class to represent threads not started here.
1105: # If they invoke anything in threading.py that calls current_thread(), they
1107: # Their purpose is to return *something* from current_thread().
1114:         Thread.__init__(self, name=_newname("Dummy-%d"))
1116:         # Thread.__block consumes an OS-level locking primitive, which
1130:         assert False, "cannot join a dummy thread"
1136:     """Return the current Thread object, corresponding to the caller's thread of control.
1138:     If the caller's thread of control was not created through the threading
1139:     module, a dummy thread object with limited functionality is returned.
1145:         ##print "current_thread(): no current thread for", _get_ident()
1151:     """Return the number of Thread objects currently alive.
1167:     """Return a list of all Thread objects currently alive.
1169:     The list includes daemonic threads, dummy thread objects created by
1170:     current_thread(), and the main thread. It excludes terminated threads and
1177: from thread import stack_size
1179: # Create the main thread object,
1185: # get thread-local implementation, either from the thread
1188: # NOTE: Thread local classes follow: the Grumpy version of this file copies
1196:         key = '_local__key', 'thread.local.' + str(id(self))
1204:         # We need to create the thread dict in anticipation of
1208:         current_thread().__dict__[key] = dict
1214:     d = current_thread().__dict__.get(key)
1217:         current_thread().__dict__[key] = d
1279:         for thread in threads:
1281:                 __dict__ = thread.__dict__
1283:                 # Thread is dying, rest in peace.
1290:                     pass # didn't have anything in this thread
1300:     # by another (non-forked) thread.  http://bugs.python.org/issue874900
1304:     # fork() only copied the current thread; clear references to others.
1306:     current = current_thread()
1308:         for thread in _enumerate():
1311:             if hasattr(thread, '_reset_internal_locks'):
1312:                 thread._reset_internal_locks()
1313:             if thread is current:
1314:                 # There is only one active thread. We reset the ident to
1317:                 thread.__ident = ident
1318:                 new_active[ident] = thread
1321:                 thread.__stop()
1368:             Thread.__init__(self, name="Producer")
1384:             Thread.__init__(self, name="Consumer")
19: #  This threading model was originally inspired by Java, and inherited
29: # Rename some stuff so "from threading import *" is safe
30: __all__ = ['activeCount', 'active_count', 'Condition', 'currentThread',
45:                         module='threading', message='sys.exc_clear')
68:                 # recursion if it has to create a DummyThread on the fly.
91:     """Set a profile function for all threads started from the threading module.
101:     """Set a trace function for all threads started from the threading module.
245:     A condition variable allows one or more threads to wait until they are
256:     """Condition variables allow one or more threads to wait until they are
374:         """Wake up one or more threads waiting on this condition, if any.
379:         This method wakes up at most n of the threads waiting for the condition
380:         variable; it is a no-op if no threads are waiting.
401:         """Wake up all threads waiting on this condition.
449:         which blocked threads are awakened should not be relied on. There is no
579:         All threads waiting for the flag to become true are awakened. Threads
590:         Subsequently, threads calling wait() will block until set() is called to
629: # Main class for threads
643:         *group* should be None; reserved for future extension when a ThreadGroup
683:         if hasattr(self, '__block'):  # DummyThread deletes self.__block
693:         # Overridden in _MainThread and _DummyThread
722:             raise RuntimeError("threads can only be started once")
763:         # reported.  Also, we only suppress them for daemonic threads;
835:                 # test_threading.test_no_refcycle_through_target when
871:         # An instance of _MainThread is always created by 'threading'.  This
874:         # same key in the dict.  So when the _MainThread instance created by
875:         # 'threading' tries to clean itself up when atexit calls this method
879:         # _active if dummy_threading is being used is a red herring.  But
880:         # since it isn't if dummy_threading is *not* being used then don't
891:             if 'dummy_threading' not in _sys.modules:
953:         It has no semantics. Multiple threads may be given the same name. The
983:         returns a list of all alive threads.
999:         The entire Python program exits when no alive non-daemon threads are
1085:         t = _pickSomeNonDaemonThread()
1088:                 self._note("%s: waiting for other threads", self)
1091:             t = _pickSomeNonDaemonThread()
1108: # They are marked as daemon threads so we won't wait for them
1117:         # can never be used by a _DummyThread.  Since a _DummyThread
1146:         return _DummyThread()
1171:     threads that have not yet been started.
1181: # (Py_Main) as threading._shutdown.
1183: _shutdown = _MainThread()._exitfunc
1189: # these from _threading_local.py to avoid circular dependency issues.
1272:             threads = _enumerate()
1274:             # If enumerating the current threads fails, as it seems to do
1292: # END _threading_local.py copy
1296:     # is called from PyOS_AfterFork.  Here we cleanup threading module state
1401:         t = ProducerThread(Q, NI)
1404:     C = ConsumerThread(Q, NI*NP)
850:         # DummyThreads delete self.__block, but they have no waiters to
1295:     # This function is called by Python/ceval.c:PyEval_ReInitThreads which
android.googlesource.com/platform/libcore:ojluni/src/main/java/java/lang/Thread.java: [ master, ]
145: class Thread implements Runnable {
575:     public Thread() {
591:     public Thread(Runnable target) {
599:     Thread(Runnable target, AccessControlContext acc) {
626:     public Thread(ThreadGroup group, Runnable target) {
638:     public Thread(String name) {
662:     public Thread(ThreadGroup group, String name) {
668:     Thread(ThreadGroup group, String name, int priority, boolean daemon) {
711:     public Thread(Runnable target, String name) {
759:     public Thread(ThreadGroup group, Runnable target, String name) {
837:     public Thread(ThreadGroup group, Runnable target, String name,
171:     private Thread         threadQ;
196:     private static int threadInitNumber;
203:     ThreadLocal.ThreadLocalMap threadLocals = null;
239:     private static long threadSeqNumber;
319:     public static native Thread currentThread();
2316:     long threadLocalRandomSeed;
2320:     int threadLocalRandomProbe;
2324:     int threadLocalRandomSecondarySeed;
197:     private static synchronized int nextThreadNum() {
209:     ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
268:     private static synchronized long nextThreadID() {
1321:     public final ThreadGroup getThreadGroup() {
50:  * A <i>thread</i> is a thread of execution in a program. The Java
54:  * Every thread has a priority. Threads with higher priority are
55:  * executed in preference to threads with lower priority. Each thread
57:  * some thread creates a new <code>Thread</code> object, the new
58:  * thread has its priority initially set equal to the priority of the
59:  * creating thread, and is a daemon thread if and only if the
60:  * creating thread is a daemon.
63:  * non-daemon thread (which typically calls the method named
77:  * There are two ways to create a new thread of execution. One is to
78:  * declare a class to be a subclass of <code>Thread</code>. This
80:  * <code>Thread</code>. An instance of the subclass can then be
81:  * allocated and started. For example, a thread that computes primes
84:  *     class PrimeThread extends Thread {
97:  * The following code would then create a thread and start it running:
103:  * The other way to create a thread is to declare a class that
107:  * <code>Thread</code>, and started. The same example in this other
123:  * The following code would then create a thread and start it running:
126:  *     new Thread(p).start();
129:  * Every thread has a name for identification purposes. More than
130:  * one thread may have the same name. If a name is not specified when
131:  * a thread is created, a new name is generated for it.
157:      * The synchronization object responsible for this thread's join/sleep/park operations.
162:      * Reference to the native thread object.
164:      * <p>Is 0 if the native thread has not yet been created/started, or has been destroyed.
174:     /* Whether or not to single_step this thread. */
177:     /* Whether or not the thread is a daemon thread. */
186:     /* The group of this thread */
189:     /* The context ClassLoader for this thread */
192:     /* The inherited AccessControlContext of this thread */
201:     /* ThreadLocal values pertaining to this thread. This map is maintained
206:      * InheritableThreadLocal values pertaining to this thread. This map is
212:      * The requested stack size for this thread, or 0 if the creator did
218:     // BEGIN Android-changed: Keep track of whether this thread was unparked while not alive.
221:      * JVM-private state that persists after native thread termination.
226:      * Indicates whether this thread was unpark()ed while not alive, in which case start()ing
228:      * the runtime, guarded by thread_list_lock. See http://b/28845097#comment49
231:     // END Android-changed: Keep track of whether this thread was unparked while not alive.
234:      * Thread ID
238:     /* For generating thread ID */
243:     /** True if this thread is managed by {@link Daemons}. */
246:     /* Java thread status for tools,
247:      * initialized to indicate thread 'not yet started'
253:     // the Thread.State enum. Android uses two sources for that information, the native thread
254:     // state and the started field. The reason two sources are needed is because the native thread
255:     // is created when the thread is started and destroyed when the thread is stopped. That means
256:     // that the native thread state does not exist before the Thread has started (in State.NEW) or
259:     // thread is in State.NEW and if started = true then the thread is in State.TERMINATED.
262:      * True if the the Thread has been started, even it has since been stopped.
280:     /* The object in which this thread is blocked in an interruptible I/O
282:      * after setting this thread's interrupt status.
299:      * The minimum priority that a thread can have.
304:      * The default priority that is assigned to a thread.
309:      * The maximum priority that a thread can have.
314:      * Returns a reference to the currently executing thread object.
316:      * @return  the currently executing thread.
322:      * A hint to the scheduler that the current thread is willing to yield
340:      * Causes the currently executing thread to sleep (temporarily cease
342:      * the precision and accuracy of system timers and schedulers. The thread
352:      *          if any thread has interrupted the current thread. The
353:      *          <i>interrupted status</i> of the current thread is
367:      * Causes the currently executing thread to sleep (temporarily cease
370:      * timers and schedulers. The thread does not lose ownership of any
384:      *          if any thread has interrupted the current thread. The
385:      *          <i>interrupted status</i> of the current thread is
426:             if (Thread.interrupted()) {
460:      * Initializes a Thread with the current AccessControlContext.
469:      * Initializes a Thread.
471:      * @param g the Thread group
473:      * @param name the name of the new Thread
474:      * @param stackSize the desired stack size for the new thread, or
487:         Thread parent = currentThread();
502:                use the parent thread group. *
530:         // Android-changed: Moved into init2(Thread) helper method.
543:         // Android-changed: Moved into init2(Thread) helper method.
552:         /* Set thread ID */
557:      * Throws CloneNotSupportedException as a Thread can not be meaningfully
558:      * cloned. Construct a new Thread instead.
569:      * Allocates a new {@code Thread} object. This constructor has the same
570:      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
573:      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
576:         init(null, null, "Thread-" + nextThreadNum(), 0);
580:      * Allocates a new {@code Thread} object. This constructor has the same
581:      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
584:      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
587:      *         the object whose {@code run} method is invoked when this thread
592:         init(null, target, "Thread-" + nextThreadNum(), 0);
596:      * Creates a new Thread that inherits the given AccessControlContext.
600:         init(null, target, "Thread-" + nextThreadNum(), 0, acc);
604:      * Allocates a new {@code Thread} object. This constructor has the same
605:      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
608:      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
611:      *         the thread group. If {@code null} and there is a security
616:      *         is set to the current thread's thread group.
619:      *         the object whose {@code run} method is invoked when this thread
620:      *         is started. If {@code null}, this thread's run method is invoked.
623:      *          if the current thread cannot create a thread in the specified
624:      *          thread group
627:         init(group, target, "Thread-" + nextThreadNum(), 0);
631:      * Allocates a new {@code Thread} object. This constructor has the same
632:      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
636:      *          the name of the new thread
643:      * Allocates a new {@code Thread} object. This constructor has the same
644:      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
648:      *         the thread group. If {@code null} and there is a security
653:      *         is set to the current thread's thread group.
656:      *         the name of the new thread
659:      *          if the current thread cannot create a thread in the specified
660:      *          thread group
673:             name = "Thread-" + nextThreadNum();
688:     private void init2(Thread parent) {
700:      * Allocates a new {@code Thread} object. This constructor has the same
701:      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
705:      *         the object whose {@code run} method is invoked when this thread
706:      *         is started. If {@code null}, this thread's run method is invoked.
709:      *         the name of the new thread
716:      * Allocates a new {@code Thread} object so that it has {@code target}
718:      * and belongs to the thread group referred to by {@code group}.
730:      * <p>The priority of the newly created thread is set equal to the
731:      * priority of the thread creating it, that is, the currently running
732:      * thread. The method {@linkplain #setPriority setPriority} may be
735:      * <p>The newly created thread is initially marked as being a daemon
736:      * thread if and only if the thread creating it is currently marked
737:      * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
738:      * may be used to change whether or not a thread is a daemon.
741:      *         the thread group. If {@code null} and there is a security
746:      *         is set to the current thread's thread group.
749:      *         the object whose {@code run} method is invoked when this thread
750:      *         is started. If {@code null}, this thread's run method is invoked.
753:      *         the name of the new thread
756:      *          if the current thread cannot create a thread in the specified
757:      *          thread group or cannot override the context class loader methods.
764:      * Allocates a new {@code Thread} object so that it has {@code target}
766:      * and belongs to the thread group referred to by {@code group}, and has
770:      * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
771:      * that it allows the thread stack size to be specified.  The stack size
773:      * machine is to allocate for this thread's stack.  <b>The effect of the
777:      * {@code stackSize} parameter may allow a thread to achieve greater
797:      * {@code Thread(ThreadGroup, Runnable, String)} constructor.
801:      * The thread stack size necessary to perform a given computation will
813:      *         the thread group. If {@code null} and there is a security
818:      *         is set to the current thread's thread group.
821:      *         the object whose {@code run} method is invoked when this thread
822:      *         is started. If {@code null}, this thread's run method is invoked.
825:      *         the name of the new thread
828:      *         the desired stack size for the new thread, or zero to indicate
832:      *          if the current thread cannot create a thread in the specified
833:      *          thread group
843:      * Causes this thread to begin execution; the Java Virtual Machine
844:      * calls the <code>run</code> method of this thread.
847:      * current thread (which returns from the call to the
848:      * <code>start</code> method) and the other thread (which executes its
851:      * It is never legal to start a thread more than once.
852:      * In particular, a thread may not be restarted once it has completed
855:      * @exception  IllegalThreadStateException  if the thread was already
862:          * This method is not invoked for the main method thread or "system"
873:         /* Notify the group that this thread is about to be started
881:         // started thread.
884:             // Android-changed: Use Android specific nativeCreate() method to create/start thread.
900:     // Android-changed: Use Android specific nativeCreate() method to create/start thread.
905:     private native static void nativeCreate(Thread t, long stackSize, boolean daemon);
908:      * If this thread was constructed using a separate
913:      * Subclasses of <code>Thread</code> should override this method.
917:      * @see     #Thread(ThreadGroup, Runnable, String)
927:      * This method is called by the system to give a Thread
949:      * @deprecated This method was originally designed to force a thread to stop
951:      *       Stopping a thread with
952:      *       Thread.stop causes it to unlock all of the monitors that it
959:      *       modifies some variable to indicate that the target thread should
960:      *       stop running.  The target thread should check this variable
963:      *       target thread waits for long periods (on a condition variable,
968:      *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
976:             if (this != Thread.currentThread()) {
977:                 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
983:             resume(); // Wake up thread if it was suspended; no-op otherwise
986:         // The VM can handle all thread states
997:      * @deprecated This method was originally designed to force a thread to stop
1000:      *        could be used to generate exceptions that the target thread was
1004:      *        are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1012:      * Interrupts this thread.
1014:      * <p> Unless the current thread is interrupting itself, which is
1016:      * of this thread is invoked, which may cause a {@link
1019:      * <p> If this thread is blocked in an invocation of the {@link
1027:      * <p> If this thread is blocked in an I/O operation upon an {@link
1029:      * then the channel will be closed, the thread's interrupt
1030:      * status will be set, and the thread will receive a {@link
1033:      * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
1034:      * then the thread's interrupt status will be set and it will return
1039:      * <p> If none of the previous conditions hold then this thread's interrupt
1042:      * <p> Interrupting a thread that is not alive need not have any effect.
1045:      *          if the current thread cannot modify this thread
1051:         if (this != Thread.currentThread())
1066:      * Tests whether the current thread has been interrupted.  The
1067:      * <i>interrupted status</i> of the thread is cleared by this method.  In
1069:      * second call would return false (unless the current thread were
1073:      * <p>A thread interruption ignored because a thread was not alive
1077:      * @return  <code>true</code> if the current thread has been interrupted;
1084:     // determines whether the interrupted status of the thread should be cleared after reading
1088:     //   thread and one to get its interrupted status.
1090:     //   the current thread can clear the interrupted status makes the code simpler as it does not
1099:      * Tests whether this thread has been interrupted.  The <i>interrupted
1100:      * status</i> of the thread is unaffected by this method.
1102:      * <p>A thread interruption ignored because a thread was not alive
1106:      * @return  <code>true</code> if this thread has been interrupted;
1121:      * Tests if some Thread has been interrupted.  The interrupted state
1133:      *     thread without any cleanup. Any monitors it held would have
1136:      *     much the manner of {@link #suspend}. If the target thread held
1138:      *     destroyed, no thread could ever access this resource again.
1139:      *     If another thread ever attempted to lock this resource, deadlock
1143:      *     Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1153:      * Tests if this thread is alive. A thread is alive if it has
1156:      * @return  <code>true</code> if this thread is alive;
1168:      * @deprecated   This method was designed to suspend the Thread but it was
1169:      *   inherently deadlock-prone.  If the target thread holds a lock on the
1171:      *   thread can access this resource until the target thread is resumed. If
1172:      *   the thread that would resume the target thread attempts to lock this
1177:      *   are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1197:      *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1209:      * Changes the priority of this thread.
1211:      * First the <code>checkAccess</code> method of this thread is called
1215:      * Otherwise, the priority of this thread is set to the smaller of
1217:      * priority of the thread's thread group.
1219:      * @param newPriority priority to set this thread to
1223:      * @exception  SecurityException  if the current thread cannot modify
1224:      *               this thread.
1243:             // Android-changed: Avoid native call if Thread is not yet started.
1248:                     // BEGIN Android-added: Customize behavior of Thread.setPriority().
1259:                     // END Android-added: Customize behavior of Thread.setPriority().
1266:      * Returns this thread's priority.
1268:      * @return  this thread's priority.
1276:      * Changes the name of this thread to be equal to the argument
1279:      * First the <code>checkAccess</code> method of this thread is called
1283:      * @param      name   the new name for this thread.
1284:      * @exception  SecurityException  if the current thread cannot modify this
1285:      *               thread.
1296:         // Android-changed: Use isAlive() not threadStatus to check whether Thread has started.
1305:      * Returns this thread's name.
1307:      * @return  this thread's name.
1315:      * Returns the thread group to which this thread belongs.
1316:      * This method returns null if this thread has died
1319:      * @return  this thread's thread group.
1323:         // Android runtime does not call exit() when a Thread exits so the group field is not
1327:         if (getState() == Thread.State.TERMINATED) {
1336:      * thread's {@linkplain java.lang.ThreadGroup thread group} and its
1338:      * thread's thread group.
1347:      *          thread's thread group and in any other thread group that
1348:      *          has the current thread's thread group as an ancestor
1355:      * Copies into the specified array every active thread in the current
1356:      * thread's thread group and its subgroups. This method simply
1357:      * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
1358:      * method of the current thread's thread group.
1364:      * thread in the current thread's thread group and its subgroups, the
1378:      *          the current thread cannot access its thread group
1380:     public static int enumerate(Thread tarray[]) {
1385:      * Counts the number of stack frames in this thread. The thread must
1388:      * @return     the number of stack frames in this thread.
1389:      * @exception  IllegalThreadStateException  if this thread is not
1403:      * Waits at most {@code millis} milliseconds for this thread to
1407:      * conditioned on {@code this.isAlive}. As a thread terminates the
1410:      * {@code notifyAll} on {@code Thread} instances.
1419:      *          if any thread has interrupted the current thread. The
1420:      *          <i>interrupted status</i> of the current thread is
1423:     // BEGIN Android-changed: Synchronize on separate lock object not this Thread.
1424:     // nativePeer and hence isAlive() can change asynchronously, but Thread::Destroy
1453:     // END Android-changed: Synchronize on separate lock object not this Thread.
1457:      * {@code nanos} nanoseconds for this thread to die.
1460:      * conditioned on {@code this.isAlive}. As a thread terminates the
1463:      * {@code notifyAll} on {@code Thread} instances.
1476:      *          if any thread has interrupted the current thread. The
1477:      *          <i>interrupted status</i> of the current thread is
1480:     // BEGIN Android-changed: Synchronize on separate lock object not this Thread.
1502:     // END Android-changed: Synchronize on separate lock object not this Thread.
1505:      * Waits for this thread to die.
1515:      *          if any thread has interrupted the current thread. The
1516:      *          <i>interrupted status</i> of the current thread is
1524:      * Prints a stack trace of the current thread to the standard error stream.
1534:      * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1535:      * or a user thread. The Java Virtual Machine exits when the only
1538:      * <p> This method must be invoked before the thread is started.
1541:      *         if {@code true}, marks this thread as a daemon thread
1544:      *          if this thread is {@linkplain #isAlive alive}
1548:      *          thread cannot modify this thread
1559:      * Tests if this thread is a daemon thread.
1561:      * @return  <code>true</code> if this thread is a daemon thread;
1570:      * Determines if the currently running thread has permission to
1571:      * modify this thread.
1574:      * is called with this thread as its argument. This may result in
1577:      * @exception  SecurityException  if the current thread is not allowed to
1578:      *               access this thread.
1579:      * @see        SecurityManager#checkAccess(Thread)
1590:      * Returns a string representation of this thread, including the
1591:      * thread's name, priority, and thread group.
1593:      * @return  a string representation of this thread.
1598:             return "Thread[" + getName() + "," + getPriority() + "," +
1601:             return "Thread[" + getName() + "," + getPriority() + "," +
1607:      * Returns the context ClassLoader for this Thread. The context
1608:      * ClassLoader is provided by the creator of the thread for use
1609:      * by code running in this thread when loading classes and resources.
1611:      * ClassLoader context of the parent Thread. The context ClassLoader of the
1612:      * primordial thread is typically set to the class loader used to load the
1623:      * @return  the context ClassLoader for this Thread, or {@code null}
1628:      *          if the current thread cannot get the context ClassLoader
1648:      * Sets the context ClassLoader for this Thread. The context
1649:      * ClassLoader can be set when a thread is created, and allows
1650:      * the creator of the thread to provide the appropriate class loader,
1651:      * through {@code getContextClassLoader}, to code running in the thread
1661:      *         the context ClassLoader for this Thread, or null  indicating the
1665:      *          if the current thread cannot set the context ClassLoader
1679:      * Returns <tt>true</tt> if and only if the current thread holds the
1683:      * the current thread already holds a specified lock:
1685:      *     assert Thread.holdsLock(obj);
1690:      * @return <tt>true</tt> if the current thread holds the monitor lock on
1701:      * of this thread.  This method will return a zero-length array if
1702:      * this thread has not started, has started but has not yet been
1710:      * <p>If there is a security manager, and this thread is not
1711:      * the current thread, then the security manager's
1719:      * this thread is permitted to return a zero-length array from this
1728:      *        getting the stack trace of thread.
1745:      * of the corresponding <tt>Thread</tt>.
1750:      * The stack trace of each thread only represents a snapshot and
1753:      * no stack trace information about a thread.
1761:      * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of
1763:      * the corresponding thread.
1768:      *        getting the stack trace of thread.
1776:     public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
1793:         Thread[] threads = getThreads();
1795:         Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
1805:         Thread[] threads = new Thread[count + count / 2];
1811:         Map<Thread, StackTraceElement[]> m = new HashMap<Thread, StackTraceElement[]>();
1844:         if (cl == Thread.class)
1868:                          cl != Thread.class;
1891:     // private native static StackTraceElement[][] dumpThreads(Thread[] threads);
1892:     // private native static Thread[] getThreads();
1895:      * Returns the identifier of this Thread.  The thread ID is a positive
1896:      * <tt>long</tt> number generated when this thread was created.
1897:      * The thread ID is unique and remains unchanged during its lifetime.
1898:      * When a thread is terminated, this thread ID may be reused.
1900:      * @return this thread's ID.
1908:      * A thread state.  A thread can be in one of the following states:
1911:      *     A thread that has not yet started is in this state.
1914:      *     A thread executing in the Java virtual machine is in this state.
1917:      *     A thread that is blocked waiting for a monitor lock
1921:      *     A thread that is waiting indefinitely for another thread to
1925:      *     A thread that is waiting for another thread to perform an action
1929:      *     A thread that has exited is in this state.
1934:      * A thread can be in only one state at a given point in time.
1936:      * any operating system thread states.
1943:          * Thread state for a thread which has not yet started.
1948:          * Thread state for a runnable thread.  A thread in the runnable
1956:          * Thread state for a thread blocked waiting for a monitor lock.
1957:          * A thread in the blocked state is waiting for a monitor lock
1965:          * Thread state for a waiting thread.
1966:          * A thread is in the waiting state due to calling one of the
1970:          *   <li>{@link #join() Thread.join} with no timeout</li>
1974:          * <p>A thread in the waiting state is waiting for another thread to
1977:          * For example, a thread that has called <tt>Object.wait()</tt>
1978:          * on an object is waiting for another thread to call
1980:          * that object. A thread that has called <tt>Thread.join()</tt>
1981:          * is waiting for a specified thread to terminate.
1986:          * Thread state for a waiting thread with a specified waiting time.
1987:          * A thread is in the timed waiting state due to calling one of
1990:          *   <li>{@link #sleep Thread.sleep}</li>
1992:          *   <li>{@link #join(long) Thread.join} with timeout</li>
2000:          * Thread state for a terminated thread.
2001:          * The thread has completed execution.
2007:      * Returns the state of this thread.
2011:      * @return this thread's state.
2015:         // get current thread state
2026:      * Interface for handlers invoked when a <tt>Thread</tt> abruptly
2028:      * <p>When a thread is about to terminate due to an uncaught exception
2029:      * the Java Virtual Machine will query the thread for its
2032:      * <tt>uncaughtException</tt> method, passing the thread and the
2034:      * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
2050:          * Method invoked when the given thread terminates due to the
2054:          * @param t the thread
2057:         void uncaughtException(Thread t, Throwable e);
2067:      * Set the default handler invoked when a thread abruptly terminates
2069:      * for that thread.
2071:      * <p>Uncaught exception handling is controlled first by the thread, then
2072:      * by the thread's {@link ThreadGroup} object and finally by the default
2073:      * uncaught exception handler. If the thread does not have an explicit
2074:      * uncaught exception handler set, and the thread's thread group
2075:      * (including parent thread groups)  does not specialize its
2085:      * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause
2115:      * Returns the default handler invoked when a thread abruptly terminates
2152:      * Returns the handler invoked when this thread abruptly terminates
2153:      * due to an uncaught exception. If this thread has not had an
2154:      * uncaught exception handler explicitly set then this thread's
2155:      * <tt>ThreadGroup</tt> object is returned, unless this thread
2158:      * @return the uncaught exception handler for this thread
2166:      * Set the handler invoked when this thread abruptly terminates
2168:      * <p>A thread can take full control of how it responds to uncaught
2170:      * If no such handler is set then the thread's <tt>ThreadGroup</tt>
2172:      * @param eh the object to use as this thread's uncaught exception
2173:      * handler. If <tt>null</tt> then this thread has no explicit handler.
2174:      * @throws  SecurityException  if the current thread is not allowed to
2175:      *          modify this thread.
2194:         Thread.UncaughtExceptionHandler initialUeh =
2195:                 Thread.getUncaughtExceptionPreHandler();
2209:      * Marks this thread as either a special runtime-managed ("system daemon")
2210:      * thread or a normal (i.e. app code created) daemon thread.)
2215:      * <p>This method must be invoked before the thread is started.
2217:      * <p>This method must only be invoked on Thread instances that have already
2223:      * @param  on if {@code true}, marks this thread as a system daemon thread
2226:      *          if this thread is {@linkplain #isAlive alive} or not a
2231:      *          thread cannot modify this thread
2345:     // BEGIN Android-added: Customize behavior of Thread.setPriority(). http://b/139521784
2347:      * Returns the thread ID of the underlying native thread -- which is different from
2348:      * the {@link #getId() managed thread ID} -- or 0 if the native thread is not
2353:     // END Android-added: Customize behavior of Thread.setPriority(). http://b/139521784
44: import dalvik.system.ThreadPrioritySetter;
51:  * Virtual Machine allows an application to have multiple threads of
65:  * Machine continues to execute threads until either of the following
71:  * <li>All threads that are not daemon threads have died, either by
86:  *         PrimeThread(long minPrime) {
99:  *     PrimeThread p = new PrimeThread(143);
187:     private ThreadGroup group;
195:     /* For autonumbering anonymous threads. */
198:         return threadInitNumber++;
202:      * by the ThreadLocal class. */
242:     // Android-added: The concept of "system-daemon" threads. See java.lang.Daemons.
250:     // BEGIN Android-changed: Replace unused threadStatus field with started field.
252:     // but in Android it is unused. The threadStatus is essentially an internal representation of
260:     // private volatile int threadStatus = 0;
265:     // END Android-changed: Replace unused threadStatus field with started field.
269:         return ++threadSeqNumber;
327:      * between threads that would otherwise over-utilise a CPU. Its use
442:         Object lock = currentThread().lock;
461:      * @see #init(ThreadGroup,Runnable,String,long,AccessControlContext)
463:     private void init(ThreadGroup g, Runnable target, String name,
479:     private void init(ThreadGroup g, Runnable target, String name,
511:         /* checkAccess regardless of whether or not threadgroup is
546:         //         ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
671:         // Must be tolerant of threads without a name.
677:         // by the runtime to construct peers for threads that have attached via JNI and it's
683:         init2(currentThread());
692:             this.inheritableThreadLocals = ThreadLocal.createInheritedMap(
721:      * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
722:      * method is invoked with the ThreadGroup as its argument.
780:      * threads to exist concurrently without throwing an {@link
846:      * The result is that two threads are running concurrently: the
863:          * group threads created/set up by the VM. Any new functionality added
868:         // Android-changed: Replace unused threadStatus field with started field.
869:         // The threadStatus field is unused on Android.
874:          * so that it can be added to the group's list of threads
891:                     group.threadStartFailed(this);
932:             group.threadTerminated(this);
938:         threadLocals = null;
950:      *       and throw a {@code ThreadDeath} as an exception. It was inherently unsafe.
954:      *       <code>ThreadDeath</code> exception propagating up the stack).  If
957:      *       other threads, potentially resulting in arbitrary behavior.  Many
967:      *       <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
982:         if (threadStatus != 0) {
987:         stop0(new ThreadDeath());
1003:      *        <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1091:     //   need to be concerned about multiple threads trying to clear the status simultaneously.
1093:     //     return currentThread().isInterrupted(true);
1142:      *     <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">
1176:      *   <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1196:      *     <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1230:      * @see        ThreadGroup#getMaxPriority()
1233:         ThreadGroup g;
1251:                     ThreadPrioritySetter threadPrioritySetter =
1254:                     if (threadPrioritySetter != null && nativeTid != 0) {
1255:                         threadPrioritySetter.setPriority(nativeTid, newPriority);
1297:         // The threadStatus field is not used in Android.
1298:         // if (threadStatus != 0) {
1335:      * Returns an estimate of the number of active threads in the current
1341:      * threads may change dynamically while this method traverses internal
1343:      * system threads. This method is intended primarily for debugging
1346:      * @return  an estimate of the number of active threads in the current
1351:         return currentThread().getThreadGroup().activeCount();
1362:      * <i>if the array is too short to hold all the threads, the extra threads
1372:      *         an array into which to put the list of threads
1374:      * @return  the number of threads put into the array
1377:      *          if {@link java.lang.ThreadGroup#checkAccess} determines that
1381:         return currentThread().getThreadGroup().enumerate(tarray);
1536:      * threads running are all daemon threads.
1596:         ThreadGroup group = getThreadGroup();
1742:      * Returns a map of stack traces for all live threads.
1743:      * The map keys are threads and each map value is an array of
1749:      * <p>The threads may be executing while this method is called.
1759:      * to see if it is ok to get the stack trace of all threads.
1785:                 SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
1789:         // Get a snapshot of the list of all threads
1790:         // BEGIN Android-changed: Use ThreadGroup and getStackTrace() instead of native methods.
1794:         StackTraceElement[][] traces = dumpThreads(threads);
1796:         for (int i = 0; i < threads.length; i++) {
1799:                 m.put(threads[i], stackTrace);
1804:         int count = ThreadGroup.systemThreadGroup.activeCount();
1807:         // Enumerate the threads.
1808:         count = ThreadGroup.systemThreadGroup.enumerate(threads);
1813:             StackTraceElement[] stackTrace = threads[i].getStackTrace();
1814:             m.put(threads[i], stackTrace);
1816:         // END Android-changed: Use ThreadGroup and getStackTrace() instead of native methods.
2016:         // Android-changed: Replace unused threadStatus field with started field.
2019:         // return sun.misc.VM.toThreadState(threadStatus);
2035:      * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
2036:      * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
2044:      * @see ThreadGroup#uncaughtException
2080:      * logging to a specific device, or file) for those threads that would
2097:      * @see ThreadGroup#uncaughtException
2120:      * @return the default uncaught exception handler for all threads
2177:      * @see ThreadGroup#uncaughtException
2207:     // BEGIN Android-added: The concept of "system-daemon" threads. See java.lang.Daemons.
2212:      * <p>System daemon threads get special handling when starting up in some
2242:     // END Android-added: The concept of "system-daemon" threads. See java.lang.Daemons.
2308:     // managed by class java.util.concurrent.ThreadLocalRandom. These
2314:     /** The current seed for a ThreadLocalRandom */
2318:     /** Probe hash value; nonzero if threadLocalRandomSeed initialized */
2322:     /** Secondary seed isolated from public ThreadLocalRandom sequence */
207:      * maintained by the InheritableThreadLocal class.
498:                 g = security.getThreadGroup();
505:                 g = parent.getThreadGroup();
544:         // if (parent.inheritableThreadLocals != null)
545:         //     this.inheritableThreadLocals =
553:         tid = nextThreadID();
613:      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
615:      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
650:      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
652:      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
684:         tid = nextThreadID();
691:         if (parent.inheritableThreadLocals != null) {
693:                     parent.inheritableThreadLocals);
743:      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
745:      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
815:      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
817:      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
871:             throw new IllegalThreadStateException();
880:         // can throw an IllegalThreadStateException if this method is called on an already
939:         inheritableThreadLocals = null;
1227:      * @see        #getThreadGroup()
1239:         if((g = getThreadGroup()) != null) {
1252:                         RuntimeHooks.getThreadPrioritySetter();
1543:      * @throws  IllegalThreadStateException
1553:             throw new IllegalThreadStateException();
1737:         StackTraceElement ste[] = VMStack.getThreadStackTrace(this);
1758:      * <tt>RuntimePermission("modifyThreadGroup")</tt> permission
2225:      * @throws  IllegalThreadStateException
2238:             throw new IllegalThreadStateException();
pdfium.googlesource.com/pdfium:third_party/libopenjpeg20/thread.c: [ master, ]
580:     opj_thread_t        *thread;
386:     pthread_t thread;
219:     opj_thread_fn thread_fn;
384:     opj_thread_fn thread_fn;
600:     opj_worker_thread_t* worker_thread;
221:     HANDLE hThread;
48: OPJ_BOOL OPJ_CALLCONV opj_has_thread_support(void)
218: struct opj_thread_t {
224: unsigned int __stdcall opj_thread_callback_adapter(void *info)
254: opj_thread_t* opj_thread_create(opj_thread_fn thread_fn, void* user_data)
277: void opj_thread_join(opj_thread_t* thread)
295: OPJ_BOOL OPJ_CALLCONV opj_has_thread_support(void)
383: struct opj_thread_t {
389: static void* opj_thread_callback_adapter(void* info)
396: opj_thread_t* opj_thread_create(opj_thread_fn thread_fn, void* user_data)
420: void opj_thread_join(opj_thread_t* thread)
433: OPJ_BOOL OPJ_CALLCONV opj_has_thread_support(void)
484: opj_thread_t* opj_thread_create(opj_thread_fn thread_fn, void* user_data)
491: void opj_thread_join(opj_thread_t* thread)
576: } opj_worker_thread_job_t;
585: } opj_worker_thread_t;
591: } opj_worker_thread_state;
599: struct opj_worker_thread_list_t {
603: typedef struct opj_worker_thread_list_t opj_worker_thread_list_t;
605: struct opj_thread_pool_t {
613:     opj_worker_thread_list_t*        waiting_worker_thread_list;
614:     int                              waiting_worker_thread_count;
625: opj_thread_pool_t* opj_thread_pool_create(int num_threads)
656: static void opj_worker_thread_function(void* user_data)
684: static OPJ_BOOL opj_thread_pool_setup(opj_thread_pool_t* tp, int num_threads)
757: static opj_worker_thread_job_t* opj_thread_pool_get_next_job(
827: OPJ_BOOL opj_thread_pool_submit_job(opj_thread_pool_t* tp,
894: void opj_thread_pool_wait_completion(opj_thread_pool_t* tp,
914: int opj_thread_pool_get_thread_count(opj_thread_pool_t* tp)
919: void opj_thread_pool_destroy(opj_thread_pool_t* tp)
606:     opj_worker_thread_t*             worker_threads;
607:     int                              worker_threads_count;
120:     /* Make sure that the TLS key is allocated in a thread-safe way */
122:     /* thread-safe, so use InterlockedCompareExchange trick */
226:     opj_thread_t* thread = (opj_thread_t*) info;
229:     thread->thread_fn(thread->user_data);
256:     opj_thread_t* thread;
258:     assert(thread_fn);
260:     thread = (opj_thread_t*) opj_malloc(sizeof(opj_thread_t));
261:     if (!thread) {
264:     thread->thread_fn = thread_fn;
265:     thread->user_data = user_data;
267:     thread->hThread = (HANDLE)_beginthreadex(NULL, 0,
268:                       opj_thread_callback_adapter, thread, 0, NULL);
270:     if (thread->hThread == NULL) {
271:         opj_free(thread);
274:     return thread;
279:     WaitForSingleObject(thread->hThread, INFINITE);
280:     CloseHandle(thread->hThread);
282:     opj_free(thread);
391:     opj_thread_t* thread = (opj_thread_t*) info;
392:     thread->thread_fn(thread->user_data);
399:     opj_thread_t* thread;
401:     assert(thread_fn);
403:     thread = (opj_thread_t*) opj_malloc(sizeof(opj_thread_t));
404:     if (!thread) {
407:     thread->thread_fn = thread_fn;
408:     thread->user_data = user_data;
412:     if (pthread_create(&(thread->thread), &attr,
413:                        opj_thread_callback_adapter, (void *) thread) != 0) {
414:         opj_free(thread);
417:     return thread;
423:     pthread_join(thread->thread, &status);
425:     opj_free(thread);
486:     (void) thread_fn;
493:     (void) thread;
579:     opj_thread_pool_t   *tp;
594:     opj_worker_thread_job_t* job;
601:     struct opj_worker_thread_list_t* next;
610:     volatile opj_worker_thread_state state;
619: static OPJ_BOOL opj_thread_pool_setup(opj_thread_pool_t* tp, int num_threads);
620: static opj_worker_thread_job_t* opj_thread_pool_get_next_job(
621:     opj_thread_pool_t* tp,
622:     opj_worker_thread_t* worker_thread,
627:     opj_thread_pool_t* tp;
629:     tp = (opj_thread_pool_t*) opj_calloc(1, sizeof(opj_thread_pool_t));
649:     if (!opj_thread_pool_setup(tp, num_threads)) {
650:         opj_thread_pool_destroy(tp);
658:     opj_worker_thread_t* worker_thread;
659:     opj_thread_pool_t* tp;
663:     worker_thread = (opj_worker_thread_t*) user_data;
664:     tp = worker_thread->tp;
668:         opj_worker_thread_job_t* job = opj_thread_pool_get_next_job(tp, worker_thread,
696:     tp->worker_threads = (opj_worker_thread_t*) opj_calloc((size_t)num_threads,
697:                          sizeof(opj_worker_thread_t));
723:         tp->worker_threads[i].thread = opj_thread_create(opj_worker_thread_function,
725:         if (tp->worker_threads[i].thread == NULL) {
737:     while (tp->waiting_worker_thread_count < tp->worker_threads_count) {
758:     opj_thread_pool_t* tp,
759:     opj_worker_thread_t* worker_thread,
782:             opj_worker_thread_job_t* job;
792:         if (!worker_thread->marked_as_waiting) {
793:             opj_worker_thread_list_t* item;
795:             worker_thread->marked_as_waiting = OPJ_TRUE;
796:             tp->waiting_worker_thread_count ++;
797:             assert(tp->waiting_worker_thread_count <= tp->worker_threads_count);
799:             item = (opj_worker_thread_list_t*) opj_malloc(sizeof(opj_worker_thread_list_t));
808:             item->worker_thread = worker_thread;
809:             item->next = tp->waiting_worker_thread_list;
810:             tp->waiting_worker_thread_list = item;
813:         /* printf("signaling that worker thread is ready\n"); */
816:         opj_mutex_lock(worker_thread->mutex);
820:         opj_cond_wait(worker_thread->cond, worker_thread->mutex);
822:         opj_mutex_unlock(worker_thread->mutex);
831:     opj_worker_thread_job_t* job;
839:     job = (opj_worker_thread_job_t*)opj_malloc(sizeof(opj_worker_thread_job_t));
866:     if (tp->waiting_worker_thread_list) {
867:         opj_worker_thread_t* worker_thread;
868:         opj_worker_thread_list_t* next;
869:         opj_worker_thread_list_t* to_opj_free;
871:         worker_thread = tp->waiting_worker_thread_list->worker_thread;
873:         assert(worker_thread->marked_as_waiting);
874:         worker_thread->marked_as_waiting = OPJ_FALSE;
876:         next = tp->waiting_worker_thread_list->next;
877:         to_opj_free = tp->waiting_worker_thread_list;
878:         tp->waiting_worker_thread_list = next;
879:         tp->waiting_worker_thread_count --;
881:         opj_mutex_lock(worker_thread->mutex);
883:         opj_cond_signal(worker_thread->cond);
884:         opj_mutex_unlock(worker_thread->mutex);
926:         opj_thread_pool_wait_completion(tp, 0);
936:             opj_thread_join(tp->worker_threads[i].thread);
943:         while (tp->waiting_worker_thread_list != NULL) {
944:             opj_worker_thread_list_t* next = tp->waiting_worker_thread_list->next;
945:             opj_free(tp->waiting_worker_thread_list);
946:             tp->waiting_worker_thread_list = next;
285: #elif MUTEX_pthread
287: #include <pthread.h>
291: /* Moved after all system includes, and in particular pthread.h, so as to */
292: /* avoid poisoning issuing with malloc() use in pthread.h with ulibc (#1013) */
310:     pthread_mutex_t mutex;
317:         if (pthread_mutex_init(&mutex->mutex, NULL) != 0) {
327:     pthread_mutex_lock(&(mutex->mutex));
332:     pthread_mutex_unlock(&(mutex->mutex));
340:     pthread_mutex_destroy(&(mutex->mutex));
345:     pthread_cond_t cond;
354:     if (pthread_cond_init(&(cond->cond), NULL) != 0) {
363:     pthread_cond_wait(&(cond->cond), &(mutex->mutex));
368:     int ret = pthread_cond_signal(&(cond->cond));
378:     pthread_cond_destroy(&(cond->cond));
398:     pthread_attr_t attr;
410:     pthread_attr_init(&attr);
411:     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
635:     if (num_threads <= 0) {
689:     assert(num_threads > 0);
698:     if (tp->worker_threads == NULL) {
701:     tp->worker_threads_count = num_threads;
703:     for (i = 0; i < num_threads; i++) {
704:         tp->worker_threads[i].tp = tp;
706:         tp->worker_threads[i].mutex = opj_mutex_create();
707:         if (tp->worker_threads[i].mutex == NULL) {
708:             tp->worker_threads_count = i;
713:         tp->worker_threads[i].cond = opj_cond_create();
714:         if (tp->worker_threads[i].cond == NULL) {
715:             opj_mutex_destroy(tp->worker_threads[i].mutex);
716:             tp->worker_threads_count = i;
721:         tp->worker_threads[i].marked_as_waiting = OPJ_FALSE;
724:                                        &(tp->worker_threads[i]));
726:             opj_mutex_destroy(tp->worker_threads[i].mutex);
727:             opj_cond_destroy(tp->worker_threads[i].cond);
728:             tp->worker_threads_count = i;
734:     /* Wait all threads to be started */
735:     /* printf("waiting for all threads to be started\n"); */