Context switching and thread state of Java thread

Keywords: Java Interview

1, Context switch:

         In concurrent programming, it is not that the more threads, the higher the efficiency. Too few threads may lead to insufficient utilization of resources. Too many threads may lead to fierce competition for resources, and then frequent context switching will cause additional overhead of the system. So what is context switching?

1. What is context switching:

         When processing multithreaded concurrent tasks, the processor will allocate CPU time slices to each thread. Threads occupy the processor and execute tasks within their allocated time slices. When the time slices of the thread run out or are forced to suspend operation for their own reasons, another thread will occupy the processor. This thread gives up the right to use the processor, Another process in which a thread obtains processor usage is called context switching.

          When a thread gives up the CPU processor, it is "cut out"; Another thread obtains CPU processor usage. It is "cut in". In the process of cut in and cut out, the operating system will save and recover relevant progress information, and this progress information is what we often call "context". The context generally includes the storage content of registers and the instruction content stored by program counters.

For a single core single thread CPU, only one CPU instruction can be executed at a certain time. From the perspective of users, computers can run multiple processes in parallel, which is precisely the result of the operating system through fast context switching. The size of each time slice is generally tens of milliseconds, so dozens or hundreds of threads may switch each other in one second, giving us the feeling that they are carried out at the same time

2. Context switching of Java multithreading:

         In Java, the context switching of multithreading is caused by the mutual switching of two running states of multithreading. The context information saved by the operating system during switching. When the thread enters RUNNABLE from BLOCKED state, that is, the thread wakes up. At this time, the thread will obtain the last saved context information, and then continue to execute according to the previous progress.

         In Java, two situations can lead to context switching: one is spontaneous context switching, that is, the switching triggered by the program itself; The other is non spontaneous context switching, that is, context switching caused by the system or virtual machine.

(1) Spontaneous context refers to thread cut-out caused by Java program call. Generally, the following methods or keywords are called during coding:

sleep(),wait(),yield(),join(),park(),synchronized,lock

(2) Non spontaneous context switching is common: the thread runs out of allocated time slices, caused by virtual machine garbage collection, or caused by execution priority problems

3. Overhead of context switching:

  • Operating system save and restore context
  • Processor cache load
  • Scheduler for scheduling
  • Context switching may cause the cache to be flushed

4. Summary:

         Context switching is a process in which one thread releases the right to use the processor and another thread obtains the right to use the processor; During cut in and cut out, the system will save and read the context information of the current thread, and the user will restore the execution progress of the thread; Both spontaneous and non spontaneous call operations will lead to context switching and system resource overhead.

         The more threads, the faster the execution speed is not necessarily. When a single logic is relatively simple and the speed is relatively fast, we recommend using a single thread. If the logic is very complex or requires a lot of computation, we recommend using multithreading to improve the performance of the system.

2, Status of Java thread:

1. Thread status description:

         Six states are defined in the java.lang.Thread.State source code of JDK. At a certain time, a thread can only be in one state:

  • New: the state of a newly created thread that has not yet started.
  • Runnable: it is in the runnable state. It has obtained all the required resources except CPU and waits for CPU scheduling.
  • Blocked: in the blocked state, the thread is blocked, waiting for the monitor to lock, and is blocked in the synchronized synchronization code block or method.
  • Waiting: waiting state. The following methods without timeout: Object.wait(), Thread.join(), LockSupport.park()
  • Timed Waiting: timeout waiting state, which specifies the thread state of the waiting time. The following methods with timeout: Thread.sleep(), 0bject.wait(), Thread.join(), LockSupport.parkNanos(), LockSupport.parkUntil()
  • Terminated: thread termination status. The thread completes execution normally or has an exception

  (1) New: a Thread class can be obtained by implementing the Runnable interface and inheriting the Thread class. When the Thread instance is created by new, it enters the new state, but the Thread has not started to execute at this time,

(2) RUNNABLE: indicates that the thread is ready for CPU scheduling and has not yet been executed. Conditions for transition to this state:

  • ① When the start() method of a thread is called, the thread does not necessarily execute immediately, because the Java thread is executed by a thread mapped to the operating system and needs to wait for CPU scheduling, but the state of the thread is already RUNNABLE

  • ② The current thread time slice has run out

  • ③ Thread.yield(): the current thread calls the yield() method to give up the obtained CPU time slice and change from the running state to the runnable state, allowing threads of the same priority to execute, but it is not guaranteed that the purpose of concession can be achieved, because the concession thread may be selected again by the thread scheduler.

  • ④ Thread end of join(): call the join() method of thread A in the current thread. The current thread blocks but does not release the object lock until thread A completes execution or the millis time expires. The current thread enters the runnable state.

  • ⑤ Thread.sleep(long millis): the current thread calls the sleep() method. The current thread enters the blocking but does not release the object lock. After millis, the thread automatically wakes up and enters the runnable state.

  • ⑥ After the thread in the lock pool gets the object lock, it enters the runnable state

(3) WAIT: WAIT state. A thread in WAIT state is waiting for another thread to perform a specific operation. For example:

  • Object.wait(): a thread calling Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on the object, which can control the execution order of threads.
  • Thread.join(): the thread is waiting for the specified join thread to terminate
  • LockSupport.park()

2. java.lang.Thread.State source code:

    public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

Reference article:

https://blog.csdn.net/qq_38862257/article/details/109685644

https://javaedge.blog.csdn.net/article/details/115721845

Posted by jburfield on Sat, 23 Oct 2021 16:06:41 -0700