Thread.currentThread() can use to get the currently executing thread. And as I think both of the sleep and yield methods are static because they can't execute sleep or yield on other threads. So by making them static it will sleep or yield only the currently executing thread.
This seems to be working in single processor system, if I callThread.currentThread() or sleep then there's only the currently running thread, it will return or it will sleep. But in a multicore system, multiple threads can run at once,
So how Thread.currentThread() or Thread.sleep() works...?
The method Thread.currentThread() returns the thread which we are currently running inside. It is simply a way of saying: "Hey give me a reference of the thread that is running me"
Suppose we have four cores and four threads A,B,C and D are running absolutely concurrently, calling this method at the same time, it will return A, B, C and D appropriately based upon the thread we are currently in.
And methods Thread.currentThread().sleep() or Thread.sleep() are doing essentially the same job. As per the documentation for currentThread():
public static Thread currentThread()
Returns a reference to the currently executing thread object.
and
public static void sleep(long millis)throws InterruptedException
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
The documentation is very poor in this case. What Thread.currentThread() returns is actually the thread where you execute that line of code in. So whether you are in a multi-processor environment or not doesn't matter in this case.
When you have two threads ThreadA and ThreadB running completely in parallel and you ask for Thread.currentThread() in parallel at the same time you will get the corresponding thread where this is executed.
These methods are static because you can access to the current execution thread of your core/CPU that is executing that code.
If there is more than one core or CPU processors, each core that passes through this code will return to you its own thread.
So you don't need to care about how many cores/CPUs are in the system, these methods will work in both scenarios a single core and multicore systems.
Remember that Java Thread is an abstraction of the OS real Thread (posix, windows...) so you can code your program without caring about OS architectures.
it works only for the "current" thread. In a multicore system if your code is single threaded only one thread is running and this is the current one so this code will work on that one. If you have multithreading program this code will work in the thread it is called. The number of cores doesn't really matter. Java distributes the threads and the load to the different cores but from code's point of view number of processors doesn't matter.
Related
In my Java application I have a Runnable such as:
this.runner = new Runnable({
#Override
public void run() {
// do something that takes roughly 5 seconds.
}
});
I need to run this roughly every 30 seconds (although this can vary) in a separate thread. The nature of the code is such that I can run it and forget about it (whether it succeeds or fails). I do this as follows as a single line of code in my application:
(new Thread(this.runner)).start()
Now, this works fine. However, I'm wondering if there is any sort of cleanup I should be doing on each of the thread instances after they finish running? I am doing CPU profiling of this application in VisualVM and I can see that, over the course of 1 hour runtime, a lot of threads are being created. Is this concern valid or is everything OK?
N.B. The reason I start a new Thread instead of simply defining this.runner as a Thread, is that I sometimes need to run this.runner twice simultaneously (before the first run call has finished), and I can't do that if I defined this.runner as a Thread since a single Thread object can only be run again once the initial execution has finished.
Java objects that need to be "cleaned up" or "closed" after use conventionally implement the AutoCloseable interface. This makes it easy to do the clean up using try-with-resources. The Thread class does not implement AutoCloseable, and has no "close" or "dispose" method. So, you do not need to do any explicit clean up.
However
(new Thread(this.runner)).start()
is not guaranteed to immediately start computation of the Runnable. You might not care whether it succeeds or fails, but I guess you do care whether it runs at all. And you might want to limit the number of these tasks running concurrently. You might want only one to run at once, for example. So you might want to join() the thread (or, perhaps, join with a timeout). Joining the thread will ensure that the thread will completes its computation. Joining the thread with a timeout increases the chance that the thread starts its computation (because the current thread will be suspended, freeing a CPU that might run the other thread).
However, creating multiple threads to perform regular or frequent tasks is not recommended. You should instead submit tasks to a thread pool. That will enable you to control the maximum amount of concurrency, and can provide you with other benefits (such as prioritising different tasks), and amortises the expense of creating threads.
You can configure a thread pool to use a fixed length (bounded) task queue and to cause submitting threads to execute submitted tasks itself themselves when the queue is full. By doing that you can guarantee that tasks submitted to the thread pool are (eventually) executed. The documentation of ThreadPool.execute(Runnable) says it
Executes the given task sometime in the future
which suggests that the implementation guarantees that it will eventually run all submitted tasks even if you do not do those specific tasks to ensure submitted tasks are executed.
I recommend you to look at the Concurrency API. There are numerous pre-defined methods for general use. By using ExecutorService you can call the shutdown method after submitting tasks to the executor which stops accepting new tasks, waits for previously submitted tasks to execute, and then terminates the executor.
For a short introduction:
https://www.baeldung.com/java-executor-service-tutorial
The link to the documentation says: Thread.sleep causes the current thread to suspend execution for a specified period
What does the term current thread mean? I mean if the processor has only one core that it makes sense to coin one of the threads as the current thread, but if all the threads(say 4 of them) are running individually on separate cores, then which one is the current thread?
The "current thread" is the thread which calls Thread.sleep(delay).
Also if a thread sleeps, it does not block the entire CPU core. Some other thread can be run on the same CPU core while your thread is asleep.
Every single command and method call you make has to be executed by anyone thread. From that thread's perspective, it is itself the current thread. So in other words: Thread.sleep(delay) pauses the thread that executes the Thread.sleep() method.
Also, keep in mind that multi-threading and multiple cores only have a very distant relationship.
Even before multi-core CPUs were commonplace, pretty much every operating system supported heavy multi-threading (or multi-tasking, which is basically the same thing for the purpose of this discussion) operation.
In modern OS this is done with a technique called preemptive multitasking. This basically means that the OS can forcibly pause the currently running process and allow another one to run for a short time, providing the illusion of actual parallel processing.
And since a lot of time in a given process is often spent waiting for some external I/O (network, disk, ...) that even means that you can use the CPU more efficiently (since the time a process would spend waiting for IO another process can spend doing actual computation).
As an example at the time of writing this, my laptop has 1311 threads (most of which are probably sleeping and only a handful will actually run and/or wait to run), even though it has only 4 cores.
tl;dr while multiple cores allow more than one thread to actually execute at the exact same time, you can have multi-threading even with a single core and there's very little noticeable difference if you do (besides raw performance, obviously)
The name, "Current thread," was chosen for the convenience of the authors of the operating system, not for the authors of applications that have to run under the operating system.
In the source code for an operating system, it makes sense to have a variable current_thread[cpu_id] that points to a data structure that describes the thread that is running on that cpu_id at any given moment.
From the point-of-view of an application programmer, any system call that is supposed to do something to the "current thread," is going to do it to the thread that makes the call. If a thread that is running on CPU 3 calls Thread.sleep(n), the OS will look up current_thread[3] (i.e., the thread that made the call) and put that thread to sleep.
From the application point-of-view, Thread.sleep(n) is a function that appears to do nothing, and always takes at least n milliseconds to do it.
In general, you should substitute "the caller" or "the calling thread" any time you see "current thread" in any API document.
If we are in a situation with two running threads on a machine with two processors and we call Thread.yield() within one of those threads, does it stand to reason that nothing will happen (the scheduler will essentially ignore the request) because we have enough processors to service the running threads?
Whenever a thread calls the Thread.yield() method, it gives a hint to the thread scheduler that it is ready to pause its execution. The thread scheduler is free to ignore this hint.
If any thread executes the yield method, the thread scheduler checks if there is any runnable (waiting to be executed) thread with same or high priority than this thread. If the processor finds any thread with higher or same priority then it will switch to a new thread. If not, the current thread keeps executing.
Since, in your example, you have enough processors to service all the Threads (they are running, not waiting in a runnable state); Thread.yield() will do nothing, and your threads will continue their execution.
A note about Windows, from Microsoft DOTNet:
This method is equivalent to using platform invoke to call the native
Win32 SwitchToThread function.
Yielding is limited to the processor that is executing the calling
thread. The operating system will not switch execution to another
processor, even if that processor is idle or is running a thread of
lower priority. If there are no other threads that are ready to
execute on the current processor, the operating system does not yield
execution
So there may be caveats in some situations.
Thread.yield() is obsolete. Unless your program is going to run on a platform that implements cooperative multitasking or on a JVM that still uses green threads, then there is no point in calling it.
The standard library Javadoc for Thread.yield() effectively says that yield() does not have to do anything at all.
I always thought that Thread::yield should be replaced with Thread::onSpinWait (since java 9) - that is just a form of a "weaker" yield, until I saw a usage of both in StampedLock:
else if ((LockSupport.nextSecondarySeed() & OVERFLOW_YIELD_RATE) == 0)
Thread.yield();
else
Thread.onSpinWait();
return 0L;
So I don't think it is obsolete. Internally in the jdk sources it has many usages, even the relatively new ForkJoinPool has usages of Thread::yield.
In practice, I have only used Thread::onSpinWait inside busy spins - because at least from the name of it - it is very clear when to use it; yielding on the other hand is not - so I can't tell for sure when and how to use it.
Just my 0.02$.
This question already has answers here:
How can threads of execution be running concurrently when there is a thread scheduler?
(5 answers)
Closed 6 years ago.
I was sure the basic term of MultiThreading was clear to me - A process is consists of multiple threads and can run them concurrently, right?
I came across this site, which declares:
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.
so what actually happens when writing:
public static void main (String [] args) {
new CalcThread("CalcThread A").start();
new CalcThread("CalcThread B").start();
}
Say the thread scheduler picked thread a to run first, and let's say thread b is going to be scheduled right after it. Is thread b going to run only after thread a has terminated?
If this is the case - why call it concurrency behaviour?
Calling start() schedules a thread to execute. While it usually executes "very soon after", actual execution commencement time is non-determinant; it's up to the JVM.
On multi-core machines, the other threads will (probably) execute concurrently on other cores while the main thread continues.
On single-core machines (eg a low spec AWS machine) the JVM may sequentially start-process-terminate each thread in turn before continuing to the main thread (I have seen this happen).
It's not necessarily when the first running thread terminates (finishes doing all of its work) but rather when its time quantum expires or other factors like you gave as examples in your post.
With preemptive scheduling, a running thread may be stopped in favor of a higher priority thread or when a new thread enters that is expected to have the shortest time to complete based on historical data. There are many factors that may be considered with thread scheduling and the algorithms used to do it.
Yes, they're running concurrently in that they both can make progress at the same time but not in parallel (actually doing work at the same instance in time).
If running on a multicore or multi processor machine where the jvm has the potential to run more than one thread absolutely simultaneously (not just apparent simultaneously), what does the api method java.lang.Thread.currentThread() return?....in the above scenario, does it just return one of the current threads at random?
It returns the thread you are currently running inside. If you have two cores and two threads A and B running completely concurrently, calling this method at the same time, it will return A and B appropriately.
Your understanding is kind-of correct - the thread returned by this method is always running - because it must be called from some thread and in order to return, it must be running. Don't think about this method in terms of: "all currently running, non-paused, non-blocked threads". Instead its meaning is: "give me a reference to the thread that runs me".
It makes perfect sense. It returns a reference to the thread that is executing the calling code.
So, suppose that you have two threads, threadA and threadB. If code running in threadA calls currentThread(), then threadA will be returned. Likewise, If code running in threadB calls currentThread(), then threadB is returned.
The documentation is pretty weak in my view. It states:
Returns a reference to the currently executing thread object.
The use of "currently" here is very poor. Currently is often interpreted to mean "at this instant in time". Which is what confused you.
Rather ironically, the MSDN (!) documentation makes a better stab at it:
Gets the Thread object that is calling the current code block.
But they still fall into the trap of using "current". Oh the pitfalls of writing technical documentation!
jvm has the potential to run more than one thread absolutely simultaneously
Yes, it is true. In a multicore / multiprocessor system it is possible to have more than one currently running thread.there are some background threads running in the JVM which you have on every system even in single processor system also.
The purpose of the method java.lang.Thread.currentThread() is to return the Thread object that is running the current code that calls the method.
java.lang.Thread.currentThread() returns the thread in which is executed the method holding your code.
That doesn't mean at all that no other threads are running at the same time.
If you want to see the difference, you may iterate on all currently running threads with this piece of code :
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getState()==Thread.State.RUNNABLE) {
// see !
}
}
(or simply count them)
It returns a reference to the currently executing thread object.
See : http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
does the api method java.lang.Thread.currentThread() returning just one thread no longer make sense
It only makes sense if you have multiple threads. It return the thread currently running the code. Something you can't obtain any other way.