This question already has answers here:
How java threads are scheduled?
(4 answers)
Closed 5 years ago.
according to the following resources, thread scheduling is done by either operation system or JVM or both.
1.http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html
2.https://www.javatpoint.com/thread-scheduler-in-java
MY QUESTION:
1.who schedules the thread?
2.does the thread scheduler gets overridden anywhere?(like OS thread being overridden by JVM thread scheduler)
3.how do i change from preemptive scheduling to time slicing scheduling ? or vice versa?
who schedules the thread?
Operating System. Though, at application level, your JRE can schedule application-level threads based on the thread priority; still it'll get scheduled finally by the scheduler(scheduling block) of OS. User level threads are managed by a user level library, but they still require a kernel system call to operate.
does the thread scheduler gets overridden anywhere?(like OS thread being overridden by JVM thread scheduler)
The Java runtime environment supports a very simple, deterministic scheduling algorithm called fixed-priority scheduling. The actual scheduler is unique in OS; and looks after scheduling of threads from overall perspective, not from Java/application level perspective.
how do i change from preemptive scheduling to time slicing scheduling ? or vice versa?
You can't change the nature of scheduling of scheduler, unless you modify the OS kernel, which is lower-level stuff. Even in JRE, you can't change the thread scheduling at the application level.
Attribution: Thread Scheduling tutorial.
JVM Schedules a Java Thread(Though in reality it is the OS doing it).
There is no single Java Virtual Machine; JVM is a specification, and there are multiple implementations of it, including the OpenJDK version and the Sun version of it, among others. Any reasonable JVM would simply use the underlying threading mechanism provided by the OS otherwise there can be discrepencies, which would imply POSIX Threads (pthreads) on UNIX (Mac OS X, Linux, etc.) and would imply WIN32 threads on Windows. Typically, those systems use a round-robin strategy by default.
3.In general the JVM doesn't do any scheduling. That is the task of the OS.
Linux for example has configurable scheduling options, and if you want to add
a new scheduling strategy, you can change the kernel.
However, depending on why you want to do this, you can solve the problem
another way such as using a custom Executor, or a Reactor style framework, or
effectively disabling scheduling for a CPU and doing all the work in Java
yourself.
Related
How do I distinguish running Java threads and native threads?
In Linux there will be Parent process for every child process, and they say 0 is the parent of all the process, will there be a Parent thread of all the forked Java threads?
How do I know which Java thread is related to OS thread (if a Java thread forkes a native process thread).
Is there any naming convention of Java threads and OS threads?
Can a running Java threads can be suspended or killed from another Java code?
On Linux, Java threads are implemented with native threads, so a Java program using threads is no different from a native program using threads. A "Java thread" is just a thread belonging to a JVM process.
On a modern Linux system (one using NPTL), all threads belonging to a process have the same process ID and parent process ID, but different thread IDs. You can see these IDs by running ps -eLf. The PID column is the process ID, the PPID column is the parent process ID, and the LWP column is the thread (LightWeight Process) ID. The "main" thread has a thread ID that's the same as the process ID, and additional threads will have different thread ID values.
Older Linux systems may use the "linuxthreads" threading implementation, which is not fully POSIX-compliant, instead of NPTL. On a linuxthreads system, threads have different process IDs.
You can check whether your system is using NPTL or linuxthreads by running the system's C library (libc) as a standalone program and looking under "Available extensions" in its output. It should mention either "Native POSIX Threads Library" or linuxthreads. The path to the C library varies from system to system: it may be /lib/libc.so.6, /lib64/libc.so.6 (on 64-bit RedHat-based systems), or something like /lib/x86_64-linux-gnu/libc.so.6 (on modern Debian-based systems such as Ubuntu).
At the OS level, theads don't have names; those exist only within the JVM.
The pthread_kill() C function can be used to send a signal to a specific thread, which you could use to try to kill that specific thread from outside the JVM, but I don't know how the JVM would respond to it. It might just kill the whole JVM.
There is no standard; this completely depends on the Java implementation which you're using. Also, don't mix up "native threads" and "native processes". A process is an isolated entity which can't see into the address space of other processes. A thread is something which runs in the address space of a native process and which can see into the memory of other threads of the same process.
What you see on Linux is something else: Some versions of Linux create an entry in the process table for each thread of a parent process. These "processes" aren't real processes (in the isolation sense). They are threads which can be listed with the ps command. You can find the process which created them by using the parent PID (PPID).
There is no generic solution how Java threads are mapped to OS threads, if at all. Every JVM implementation can do it in a different way.
There is also a pure Java thread implementation, called green threads. This is used as a fallback if native threads aren't supported or the system isn't multithreaded at all. You won't see any green threads at your OS.
Can a running Java threads can be suspended or killed from another Java code ?
If they are running at the same JVM, yes, with stop(). But that's not a good solution and may work, or not. interrupt() allows the thread so safely shut itself down.
There is no way to kill threads outside of the JVM I know of. If a OS really supports killing of threads, I wouldn't expect the Java application to run correctly afterwards!
Can a running Java threads can be
suspended or killed from another Java
code ?
In theory yes. In practice, the Thread.kill() and Thread.suspend() methods are deprecated because they are unsafe except in very limited situations. The basic problem is that killing or suspending a Java thread is likely to mess up other threads that depend on it, and shared data structures that it might have been in the middle of updating.
If "another Java code" is meant to mean another JVM, then the chances of it working are even less. Even if you figured out how to send the relevant thread signal, the results are completely unpredictable. My bet is that the "target" JVM would crash.
Below is what I have seen on java t point about thread scheduler.
Thread Scheduler in Java
Thread scheduler in java is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
The source you are quoting sounds somehow outdated. In present day JVM implementations, Java uses underlying operating system threads.
In other words: a Java thread is mapped by the JVM to a thread provided by the operating system. See here for example.
In that sense, the "true" multi-threading capabilities of your system very much depend on the JVM implementation/version and the OS type/version; and even the capabilities of the underlying hardware. But rest assured: on a current day system, Java is able to run many threads in "real parallel".
In your context - Java used "green threads" at some point (and then Java would manage the threads) - but that is computer science history (many many years in the past). See here for example.
Thread scheduler in java is the part of the JVM that decides which thread should run.
Close, but... Most JVMs that anybody uses for real work in the last couple of decades use "native threading". That means, that scheduling is the operating system's job. The JVM does not get involved.
There is no guarantee [of] which runnable thread will [next] be chosen to run by the thread scheduler.
True but..., The operating system implements a thread scheduling policy (It may be capable of implementing any of several policies, to be chosen by the system administrator). If you understand the policy, then you could, in principle, know which thread will be scheduled next.
But true, because the Java Language Specification does not say anything about thread scheduling policies, and if you're writing a "run anywhere" Java program, then you should not depend on any particular policy.
Only one thread at a time can run in a single process.
False, but... It was true, maybe thirty years ago. Virtually all computers, tablets, and cell phones these days have more than one processor. At any given instant, there can be one thread running on each processor.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
Yes. The thread scheduler on any given OS doesn't mainly do whatever, it implements a policy. On most computers, tablets, and cell phones the policy choices all will be preemptive. That means that a thread could be be de-scheduled at any point in time (e.g., half way through an i++; statement).
The alternative to preemptive multi-tasking is called cooperative multitasking, in which a thread can lose its turn on the processor only at certain, well defined yield points. That's what Thread.yield() is for, but I don't know where you are ever going to find Java running in a cooperative multitasking environment.
You can run more than one thread in a process at the same time if your machine supports that.
Information you have is very obsolete. What you describe was valid for OS when each process was effectviely a single thread (Windows 3.1, or OLD unix kernels, Macintosh system 7). That time JVM running as a single process had to implement its own thread scheduler and thread management.
Today all common platforms support natively multithreading and by default JVM uses the underlying system implementation
I've read somewhere that in Java scheduler, thread switching happens after execution of certain amount of instructions and not after a certain time (like schedulers used in operating systems). But the references were missing. I wanted to know if this is correct.
Java used to have a feature called GreenThreads, It was removed in 1.3. For all practical purposes we can assume that thread scheduling is directly influenced by the underlying operating systems's process/thread scheduling strategy. In this context, developers need to assume that threads are executed/scheduled randomly and should code/treat them as such.
On Linux the scheduling of Java threads is done using the Completely Fair Scheduler (CFS). For each CPU there is a run-queue and by default there is 24 ms in which all threads on a single-run queue should have a chance to run. So if there are 2 threads, each thread gets 12 ms, if there are 3 tasks, each thread gets 8 ms.
When tasks have a different priority, things chance. And also there is a minimum granularity to prevent reduce context switching overhead of many threads are running.
In Java: Is it possible to prevent the scheduler (Ubuntu) to do a context-switch on a specific part of a thread-code.
And if so, how?
You should go for a realtime thread:
http://jrate.sourceforge.net/api/stable/javax/realtime/RealtimeThread.html
and set its priority to the maximum level:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#setPriority%28int%29
This way, once the realtime thread is started, it won't release the processor anymore.
More, the scheduler should be asked to behave like a (realtime) FIFO scheduler.
You have a setScheduler() method.
What I do to avoid context switching is use thread affinity, busy waiting and isolating the cpus (if the OS supports that) Java doesn't support these so well but with the help of a little JNI/JNA it can be done.
Thread Affinity library for Java
Note: There are NMI interrupts which cannot be prevented but usually don't have much impact.
I read some tutorial about threads and processes, it is said that the processes be scheduled by operating system kernel, and the threads can be managed and scheduled in a user mode.
I do not understand the saying "threads can be managed and scheduled in a user mode",
for example: the producer and consumer problem? is this a example for "scheduled in a user mode"? or can anyone explain me?
Not sure what tutorial you're looking at, but there are two ways that threads can be scheduled.
The first is user-mode scheduling, which basically mean that one process, using Green threads or perhaps fibers, schedules different threads to run without involving the operating system in its decision. This can be more portable across operating systems, but usually doesn't allow you to take advantage of multiple processors.
The second is kernel scheduling, which means that the various threads are visible to the kernel and are scheduled by it, possibly simultaneously on different processors. This can make thread creation and scheduling more expensive, however.
So it doesn't really depend on the problem that you are trying to solve. User-mode just means that the scheduling of threads happens without involving the operating system. Some early Java versions used Green/user-mode threads, but I believe most now use native/kernel threads.
EDIT:
Coding Horror has a nice overview of the difference between user and kernel mode.
Get a better tutorial? The official Java tutorials are quite good, and contain a lesson on concurrency, that also defines what process and thread mean.
PS: Whether threads are managed/scheduled in user mode is an implementation detail of the Java Virtual Machine that generally need not concern the application programmer.
Scheduled in user mode means you have control over the threads of your software but they are managed by the operating system kernel. So yes, the producer consumer problem is an example you normally handle yourself (but it is not directly related to user mode scheduling) by having two threads, a producer thread and a consumer thread. Both threads access the same shared recource. This resource has to be thread-safe, this means you have to make sure the shared resource does not get corrupted becouse both threads access it at the same time. Thread safety can either be guaranteed by using thread-safe data types or by manually locking or synchronizing your resource.
However, even if you have some control over your threads e.g. starting threads, stopping threads, make threads sleep etc. you do not have full control. The operating system is still managing which threads are allowed cpu time etc.