15

I am new to Java technology. I know that there is only two ways to create Thread in Java

  • Extending Thread class
  • Implementing Runnable Interface

So this is only two ways of creating Thread. But when we start our Program with main JVM started one main Thread. I think even JVM has to follow the rule for creating main Thread means for creating main thread JVM either has to extend Thread class or implement Runnable.

public class MainThreadExample {

    public static void main(String[] args) {

        Thread t=Thread.currentThread();            
        System.out.println(t.getName());            
    }
}

I tried my level best but not able to know how JVM created this main object. As I entirely went through main class (sun.tool.jar) I know this is the class which is responsible for main thread.But after searching so many web page in Google not able to get it. So please help and if possible refer me the example or link also.

P.S: I am learning Java technology, I should not have bother this how they created main and all it's a designing thing. But I think its a logical question to ask

Ian R. O'Brien
  • 6,682
  • 9
  • 45
  • 73
Arun
  • 1,038
  • 2
  • 12
  • 25
  • 1
    I would guess it's an anonymous subclass of `Thread` – John Dvorak Jul 02 '13 at 18:23
  • What does `t.getClass().getFullName()` say? – John Dvorak Jul 02 '13 at 18:23
  • there is no any rule that if we don't see the Runnable and Thread guys so there is no any thread, a method would fired by a thread, you can also run every thread by reflection while they are not a void run(), JVM creates a thread and inside the thread calls the main method –  Jul 02 '13 at 18:25
  • 1
    I don't think the Java runtime itself has to follow Java rules for creating a thread, as it's not implemented in Java. I suspect the garbage collector also runs in its own thread, and (as far as I know) the GC does things that cannot be done in Java. – Reinstate Monica -- notmaynard Jul 02 '13 at 18:25
  • 3
    Not related to answer, I found this detailed article on threads in java. I think you'd like reading. http://blog.jamesdbloom.com/JVMInternals.html – ata Jul 02 '13 at 18:35

2 Answers2

21

An instance of java.lang.Thread is not a thread; it can be used to represent a thread of execution in the JVM but the JVM is perfectly capable of creating threads without using the Thread class at all.

This is what happens with the main thread: the JVM creates it, and an instance of java.lang.Thread is created to represent it later.

In the Hotspot JVM there's a lot of threading related code in the Threads class defined in src/share/vm/runtime/thread.hpp and src/share/vm/runtime/thread.cpp. The startup of the JVM calls the static Threads::create_vm function, which is already running in a thread set up by the operating system. Within that function we find:

(src/share/vm/runtime/thread.cpp)
3191   // Attach the main thread to this os thread
3192   JavaThread* main_thread = new JavaThread();
3193   main_thread->set_thread_state(_thread_in_vm);
3194   // must do this before set_active_handles and initialize_thread_local_storage
3195   // Note: on solaris initialize_thread_local_storage() will (indirectly)
3196   // change the stack size recorded here to one based on the java thread
3197   // stacksize. This adjusted size is what is used to figure the placement
3198   // of the guard pages.
3199   main_thread->record_stack_base_and_size();
3200   main_thread->initialize_thread_local_storage();

The JavaThread class is apparently used for bookkeeping; it associates an OS or VM thread with a Java Thread object. The Java object apparently doesn't exist yet. The code then goes on to initialize various other things, and later on still in the same function we find this:

3335     // Initialize java_lang.System (needed before creating the thread)
3336     if (InitializeJavaLangSystem) {
3337       initialize_class(vmSymbols::java_lang_System(), CHECK_0);
3338       initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0);
3339       Handle thread_group = create_initial_thread_group(CHECK_0);
3340       Universe::set_main_thread_group(thread_group());
3341       initialize_class(vmSymbols::java_lang_Thread(), CHECK_0);
3342       oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0);
3343       main_thread->set_threadObj(thread_object);
3344       // Set thread status to running since main thread has
3345       // been started and running.
3346       java_lang_Thread::set_thread_status(thread_object,
3347                                           java_lang_Thread::RUNNABLE);

In other words, we it initializes the System, ThreadGroup, and Thread classes, then creates an instance of Thread referenced by thread_object (line 3342), and sets the Thread instance for the main JavaThread.

If you wonder what the create_initial_thread does, apparently it allocates the Thread instance, stores a pointer to the JavaThread (C++) object in the private eetop field of the Thread instance, sets the thread priority field to normal, calls the Thread(ThreadGroup group,String name) constructor, and returns the instance:

 967 // Creates the initial Thread
 968 static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) {
 969   klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_     NULL);
 970   instanceKlassHandle klass (THREAD, k);
 971   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL);
 972 
 973   java_lang_Thread::set_thread(thread_oop(), thread);
 974   java_lang_Thread::set_priority(thread_oop(), NormPriority);
 975   thread->set_threadObj(thread_oop());
 976 
 977   Handle string = java_lang_String::create_from_str("main", CHECK_NULL);
 978 
 979   JavaValue result(T_VOID);
 980   JavaCalls::call_special(&result, thread_oop,
 981                                    klass,
 982                                    vmSymbols::object_initializer_name(),
 983                                    vmSymbols::threadgroup_string_void_signature(),
 984                                    thread_group,
 985                                    string,
 986                                    CHECK_NULL);
 987   return thread_oop();
 988 }

Now, this is what the Hotspot VM does. Other implementations, like IBM J9, Oracle JRockit, or Azul Zing probably do something similar though.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • Thank you so much for answering Joni.But can you please little bit elaborate how Java made that Java.lang.Thread instance to represent it.I went through the entire main and Thread class but did not get it – Arun Jul 02 '13 at 18:33
  • The main thread and the `java.lang.Thread` object that represents it has to be created in native code. I'll have a look at the OpenJDK sources, maybe I can pinpoint the location. – Joni Jul 02 '13 at 18:37
  • It would be great help..Thank you soo much for helping – Arun Jul 02 '13 at 18:41
  • See update, ask if something's not clear, it gets complicated to explain when Java and C++ objects are used together and mixed like this. – Joni Jul 02 '13 at 22:28
3

I believe the exact mechanics are JVM specific. The specs are a little vague, but the Thread Javadoc offers the following:

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class).

How this maps onto an instance of the Thread class does not appear to be specified.

NPE
  • 486,780
  • 108
  • 951
  • 1,012