For the below program different outputs are coming when running and debugging on eclipse.
public class MyClass implements Runnable {
public static void main (String[] args) throws Exception {
Thread t = new Thread(new MyClass());
t.start();
System.out.print("Started");
t.join();
System.out.print("Complete");
}
public void run() {
for (int i = 0; i < 4; i++) {
System.out.print(i);
}
}
}
When running this as java application the OUTPUT is
Started0123Complete
When checking in Debug Mode OUTPUT is
0123StartedComplete
Can someone help on this? is it because of two threads? main thread and the thread which starts with t.start().If yes then why main thread execution is taking more priority to complete first?
Thanks
The order in which the string "Started" and the integers are printed out is undefined by definition. After you call start, there is no guarantee that the code in the run method will be executed before or after any other statement that appears before the call to join. This is the nature of multithreaded applications.
The fact that you see a certain output in debug mode vs run mode is probably purely accidental and might change if you run your code many times or on different platforms/versions of the JVM. If you need deterministic order in this case, the only way you can achieve it is to print a string before calling start or introduce some other sort of semaphore to force the thread to wait for the main thread or viceversa.
It's coincidence. You can't control the thread scheduler.
However, in a debug environment, the debugger plugs into your code to inspect values and execution. This inspection increases the amount of work done per thread time slice.
For example, in a regular run, the main thread may only need 1 time slice to create the new thread object, start it, and print the Started message. Then a context switch would occur and the second thread would get a chance to work. In a debug run, the main thread would only have enough time to create the new thread object and start the corresponding thread. Then the context switch would occur and the other thread would do its thing.
It is not related to being in debug mode or not.
There is no guarantee of when this gets executed
System.out.print("Started"); //this is in the main thread
compared to
for (int i = 0; i < 4; i++) { // this is in the started thread
System.out.print(i);
}
It can even be
01Started23Complete
Yes, Its because of 2 threads But the output is unpredictable.
No, the main thread doesn't get high priority because its MAIN.
you can't say any particular interleaved execution in multithreads.
In Debug, my guess is you put a break point for main thread so it waits and in the mean time the other thread might have executed.
In both (Run / Debug) the mode output will be
Started0123Complete
You are seeing result 0123StartedComplete, because you must be having debug point inside main thread code, that’s why.
If you want to understand better, then move the run() method to inside MyClass and put debugger point inside run method now you will see it is printing as Started0123Complete.
Internally, Main Thread is creating subthread “t” and when t.start() is being called it is waiting to capture the monitor for thread execution (i.e. run()) and when you are adding debug statement in main thread, sub-thread is entering into monitor and run method is executing and once it completed, main thread is starting again.
Related
My task is to create x Threads, and in some way to use MethodA and B, and synchronize them, and to catch some Exception in the end.
I know this is not a really good description of the task, but this is how I got the task.
So the question is, would this code do, what the task is asking for?
Are these Threads synchronized correctly or not?
public class Test2{
public static synchronized void doActionA(){
System.out.println("Hi");
}
public static synchronized void doActionB(){
System.out.println("Hello");
}
public static void main(String[] args) {
for(int i = 0; i < 10000; ++i){
try{
new Thread(() -> {
doActionA();
doActionB();
}).start();
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println(":)");
}
}
}
}
This is mostly useless, yeah.
You have 10000 threads. Each thread is going to perform the following task pattern:
NB: Take the object "Test2.class" (the instance of java.lang.Class that represents the Test2 class; there is only one such object in the entire VM loaded. We shall call this 'the locker'.
Check the locker object for its 'monitor' thread. If it is unset, set yourself as the monitor thread of the locker and continue. (and do all that atomically). If not, freeze the thread until the 'monitor' is null again, and then compete with the 9999 other threads that want to set it; only one of the 9999 wins, sets itself as the monitor, and continues. The remainining 9998 will freeze and wait another round.
Execute doActionA. All the while, 9999 threads are twiddling thumbs.
Relinquish the locker (unset yourself as the monitor of the locker). 9999 other threads all fly in to set themselves as monitor. Only one of those will 'win'.
Acquire the lock again (set yourself as the monitor of the locker if it is currently unset; otherwise, freeze and wait until it is available.. and do that atomically). Depending on the JVM implementation, this thread may in fact 'win', and take the monitor riiight back, beating the other 9999 threads.
Execute doActionB. During this job, 9999 threads are twiddling thumbs doing absolutely nothing whatsoever. Just waiting around.
Relinquish the monitor and exit. Pfew. 9999 more to go.
As you can tell, this pattern most likely means this code runs as fast as just:
for (int i = 0; i < 10000; i++) {
doActionA();
doActionB();
}
except the above most likely runs FAR faster, as your example first allocates 1.25 gigabytes worth of memory just to store stacks (each thread needs a stack, and here's praying your stacks are 'just' 128k large, they are often larger), and wastes a ton of time juggling thread states for pretty much no purpose.
This is not how you thread things.
Are these Threads synchronized correctly or not?
"Synchronized" in what way? "Synchronized" for what purpose?
It's "correct" if the program is guaranteed to do what you want it to do. What do you want this program to do?
What it will do is, it will print print ten thousand complete lines of "Hi", and it will print ten thousand complete lines of "Hello", and it will print them in no particular order. The reason each line will be complete is that the System.out object uses synchronization to ensure that at most one thread at a time can execute println(...). The reason why the lines will be printed in no particular order is, there isn't any other synchronization between the threads in the program.
This is the main part of your task:
catch some Exception in the end.
The question is: would this code do what the task is asking for?
No, becasue exception happened inside a thread can not be caught outside of the thread like this, read the following question for more information:
How to catch an Exception from a thread
I have a small test using just two threads as follows:
import static java.lang.System.out;
#Test
public void testTwoSimpleThreads() {
doInParallelAsync(() -> {
out.println("First Ok");
},
() -> {
out.println("Second Ok");
});
}
private void doInParallelAsync(Runnable first, Runnable second) {
new Thread(() -> {
first.run();
}).start();
new Thread(() -> {
second.run();
}).start();
}
Sometimes the output will only include one of them before I introduced join() after they're started.
Two different outputs I encountered so far:
one
First Ok
Two
First Ok
Second Ok
I know the println() is synchronized and also I know the threads created by main thread are user threads in default and user threads will not exit until they finish.
Though I am using #Test, I tested it that they're non-daemon as expected.
non-daemon
is a daemon thread if and only if the creating thread is a daemon
And
The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
UPDATED
Actually I know what the answers point out, I wonder why the output disappear?
Questions I need to ask:
The pipeline closed by the main thread?
Why? Is it because each pipeline is bond to one thread independently? Not shared? (that the pipeline won't be closed until the last thread finish just like the reference counting - the file will not be deleted until no one is using it)
The last question: is it controlled by JVM or dependent upon the OS?
It seems the pipeline is closed by the #Test I mentioned. Thank you, #meriton for pointing it out.
Conclusion
When I tried this method in an ordinary main(), and directly invoke System.exit(0); just right after the start(), the output is quite the same as that when using #Test.
When using #Test (Junit), the threads will not be waited. For more details, please check JUnit test not executing all threads created within the test and JUnit terminates child threads.
And here is an explanation from #Alex Lockwood which I personally prefer:
JUnit is a unit testing framework... as with the Android framework, it has a main thread from which it will call user-defined unit test methods. When a unit test returns, JUnit immediately invokes the next unit test method (or exits completely if there are no more unit test methods to call). JUnit doesn't know anything about the background threads you create/start, so you can't assume that it will sit around and wait for them to finish.
Might the test runner invoke System.exit() after all tests have run? Can you reproduce the partial output if you convert the test into an ordinary main() method?
(I'd try myself, but was unable to reproduce a partial output when running this as a JUnit test in eclipse)
... and no, System.out is a static field, and hence shared by all threads. Exiting the main thread does not close the stream.
Thats because you started them on a different thread and the main thread do not wait for child threads to complete and will close its execution immediately after last line.
So, by that time if Thread 1 is executed Output will be:
First Ok
If Thread 2 is executed:
Second Ok
And if by luck both got executed then
First Ok
Second Ok
or
Second Ok
First Ok
By providing join, you are asking main thread to wait for the child thread to be completed and hence both the outputs.
-- EDITED --
This doesn't mean that the child threads were terminated, they still completed their execution but you may not be able to see the results as outstream may have been closed or released by that time
If you execute the same command on Jshell, you will always get the second output, but sometimes it come in as another command, because as soon as main thread completes, Jshell moves to next command line:
I have Main class with main method. I create two Threads What i noticed that code from main thread executes before created Threads. What i was expecting is to run it simultaneous. Why code from main method executes berofe code from Threads?
Main.class:
public class Main extends Thread {
public static void main(String[] args) {
NewThread thread = new NewThread("Thread1");
NewThread thread2 = new NewThread("Thread2");
for (int i = 0; i <3 ; i++) {
System.out.println("From main thread");
}
thread.start();
thread2.start();
}
}
NewThread.class
public class NewThread extends Thread{
public NewThread(String name) {
this.setName(name);
}
public void run() {
int clientnumber = 1;
while(clientnumber!= 3) {
System.out.println("server sent data to client: " + getName());
clientnumber++;
}
}
}
Output:
From main thread
From main thread
From main thread
server sent data to client: Thread2
server sent data to client: Thread1
server sent data to client: Thread2
server sent data to client: Thread1
Why code from main method executes before code from Threads?
Simply, because it can.
When you start() a thread, either the parent thread or the child thread may be scheduled to run next. Or they may both scheduled simultaneously. Or an entirely different thread may be scheduled.
The Java language and runtime system make no guarantees of thread scheduling order. Furthermore thread scheduling behavior is liable to be different for different execution platforms1; e.g. depending on how many cores you have.
(Why? Because, this is how native thread scheduling works on a typical OS. Java can't fight this and still use native threads. Using user-space threads and thread scheduling has serious performance issues. Sun abandoned that approach decades ago.)
What do you do to solve this?
Don't make assumptions about scheduling, and the order in which threads will execute.
If your application really needs one thread to run before the other, use one of the concurrency primitives or classes to achieve it ... explicitly. (But beware that by forcing one thread to run before another you are reducing the effective concurrency.)
In your example, the problem is basically that your expectations were incorrect. It is no longer a problem once you have adjusted your expectations.
1 - Behavior is likely to be repeatable on a given platform, especially in a small / simple example like yours. But then again, it could change if you ran your test while the system was under heavy load. Remember: No guarantees!
Execution of other threads starts with .start() method - you call this method after loop printing informations to the console in `main.
EDIT: These lines are printed before lines from new threads, because it is likely to be faster to print 3 lines to the console than perform loops in other threads and then print. After edit that you made to the question - to see how all three threads (including thread containing main()) are working in the same time and to see the difference in order of printed lines - I suggest you to try one of the following ways to see the difference:
Try to perform time-consuming operation in main() after starting new threads and before printing to the console in main() (you can think of that operation on your own or try one of these listed in these answers, or
Try to increase number of loops (maybe even to few thousands) with statements printing to the console in each thread - you'll see that all threads work in the same time, or
Simply call Thread.sleep(1000) (or higher number as the argument - it's number of milliseconds that you want the current thread to sleep) in main() after starting new threads and before printing lines from the main().
NewThread thread has to be started before it will start executing. You are starting both threads only after main() has processed the loop. What you want is probably:
new NewThread("Thread1").start();
new NewThread("Thread2").start();
for (int i = 0; i <3 ; i++) {
System.out.println("From main thread");
}
However it's up to JVM and OS to schedule the threads. You still might observer the main() executing first before NewThread gets a chance to run.
I just stumbled upon a weird behavior of daemon threads which I can't explain. I've reduced my code to a minimal, complete and verifiable sample:
public static void main(String[] args) throws InterruptedException {
Thread runner = new Thread(() -> {
final int SIZE = 350_000;
for (int i = 0; i < SIZE; i++) {
for (int j = i + 1; j < SIZE; j++) {
if (i*j == SIZE * SIZE - 1) {
return;
}
}
}
});
runner.setDaemon(true);
runner.start();
// Thread.sleep(1000);
System.out.println("Exiting.");
}
The code executed by the runner thread takes about 12 secs to terminate on my box, and we're not interested in what it does, since I just needed to spend some time computing.
If this snippet is run as it is, it works as expected: it terminates just after its start.
If I uncomment the Thread.sleep(1000) line and run the program, it works for about 12 seconds, then prints out "Exiting" and terminates.
As far as I understood how daemon threads work, I expected this code to run for 1 second and then to terminate execution, since the only user thread running is the one launched with the main() method (the runner is a background daemon thread) and as soon as the 1000 msec are passed, it reaches the end of its execution and the JVM should stop. Also, it looks quite strange that "Exiting" is printed only after 12 seconds, and not when the program starts.
Am I wrong? How can I achieve the desired behavior (pause for a second and then stop, independently from what the runner thread is doing)?
I'm using a 64bit Oracle JDK 1.8.0_112 on a linux box and it has the same behavior either if launched from an IDE or from the command line.
Thanks,
Andrea
This is maybe a consequence of counted loop optimization which removed safepoint polls from your nested loops. Try to add -XX:+UseCountedLoopSafepoint flag to your JVM startup options.
Thread#sleep(long) pauses the main thread before it returns from its main method (i.e. before the JVM is considering the program done as long as no non-deamon threads are alive). The scheduler is then free to run any other runnable thread which would be the deamon thread. As it stands, there is no apparent reason for the JVM to forcibly preempt the deamon thread before it finishes execution to continue in the main thread (is it's done sleeping yet), so the JVM is free to continue its schedule. However, it may at any time elect to pause the running thread and schedule another runnable thread for execution, so reproducibility is not guaranteed for your example.
You can force a preemption by inserting calls to Thread#yield() or #sleep(1) in the loops. I bet you'll start seeing the snippet exiting faster and before it finishes the loops.
There's more to learn about Thread states and scheduling, a nice overview can be found here.
Update for comment:
I cannot modify the code in the background thread (is a requirement), so I was looking for a way to stop it if it takes too long (a description of what I'm doing is stackoverflow.com/questions/41226054/… ).
It's legally only possible to stop a running thread from within, so you usually have it test an abort condition every iteration, and if the condition is met, the run method return;s. An abort condition could be as simple as a boolean flag that is set from the outside (! volatile caveat !). So the dead-simplest solution would be to have the main thread set such a flag after the sleep.
Another possibility might be using an ExecutorService that supports timeouts, see this Q&A for an example involving ScheduledExecutorService.
Still I don't understand how the scheduler can decide to wait for 12 seconds before running the System.out instruction.
It does not wait 12 seconds, it let's the deamon thread run to completion because being a deamon only matters to the JVM when deciding if it's safe to halt the JVM. For the scheduler, only the state of the thread matters and as far as it's concernced, after the 1s sleep of the main thread, it has a running (deamon) and a runnable thread (main), and no indication that the running thread should be paused in favor for the runnable thread. Switching threads is also expensive computationally, so the scheduler might be reluctant lacking any indication. An indication to switch might be sleeps and yields, but also GC runs and a whole lot of other things.
In the below code what could be the predicted output?
public class Threads2 implements Runnable {
public void run()
{
System.out.println("run.");
throw new RuntimeException("Problem");
}
public static void main(String[] args)
{
Thread t = new Thread(new Threads2());
t.start();
System.out.println("End of method.");
}
}
The possible outcome given as the answers are:
End of method.
run.
java.lang.RuntimeException: Problem
OR
run.
java.lang.RuntimeException: Problem
End of method.
According to me only answer 2nd is possible, please help me to understand.
Both answers are possible. It's up to the thread scheduler to decide when instructions of concurrent threads are executed. The started thread and the main thread are run "in parallel", and the only guarantee is that the each thread's instructions are executed in sequence. But there could be any interleaving betwen the two sequences of operations.
You could also have the following, BTW.
run
end of method
java.lang.RuntimeException: Problem
To make an analogy, imagine you have a hurdle race, and you tell each runner to start the race, one at a time. Do you know which runner will come at each hurdle in first position? No, you don't. It depends on the speed of each runner. If the first runner to start is very slow, the last runner could come at the first hurdle before him. That's the same with threads. The scheduler assigns each running thread to a core, in any order he wants to, and for any time it decides. The only guarantee you have is that each thread will be executed some time.
t.start(); tells the system to start the thread - nothing says that the system has to actually give the thread execution time right away.
Another possibility is:
run.
End of method.
java.lang.RuntimeException: Problem
The execution will result in two threads, the main thread (the one running the main-method), and the thread created in the main method. Since you can't guarantee anything when it comes to the order that the threads will run, there are multiple orders that the code could run.
So lets call the main thread Thread1, and the created thread Thread2. The possibilties then are, after Thread2 has been started:
Thread1 gets the processor time first. ("End of method..." get printed first)
Thread2 gets the processor time first. ("run" get printed first)
and, there is actually a third possibility (i think):
Thread2 get the processor time and prints "run".
Thread2 gets interupted, and Thread1 takes over.
Thread1 prints "End of..."
Thread2 throws the exception.
First of all, note that the Exception's stack trace is usually printed to the stderr stream of the process, while you write to the stdout. Often stderr is redirected to stdout, but this is not required.
Another thing to consider is that the documentation doesn't state anything about the concurrent access of PrintStream#println(), so the output when two threads try to print at the same time is truly umpredictable.
Given that it doesn't make much sense to have the exception stack trace in the game (because it's another stream altogether), the problem is reduced to which between the main thread and the other one writes first. Not only this is up to the JVM scheduler, but also consider that the method is not synchronized, so it could even print an interleaved string (well, I don't think this will ever happen in reality, but this is what may happen).
I think your question is "why can the output of 'run' be printed after the exception is printed". They are in the same thread, and should execute in sequence, which should guarantee System.out.print("run"); execute first then throw new RuntimeException("Problem");is executed after that.
The problem here is those two lines of code uses different printing queue. System.out.print() use the standard output, while the error message caused by throw new RuntimeException("Problem");will go to the standard error output. So which message prints first not only depends on which line of code gets executed first, but also which output queue flushed to screen first.
If the second line of code is System.out.print("problem"); then 'problem' will always print after 'run' since they are using the same output queue