Java Thread random output - java

public class Rough {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread1 testThread1 = new TestThread1();
TestThread2 testThread2 = new TestThread2();
testThread1.start();
testThread2.start();
// testThread1.stop();
System.out.println(testThread1.getName());
System.out.println(testThread2.getName());
}
}
class TestThread1 extends Thread {
public void run() {
System.out
.println("MyThread1 running :: " + System.currentTimeMillis());
}
}
class TestThread2 extends Thread {
public void run() {
System.out
.println("MyThread2 running :: " + System.currentTimeMillis());
}
}
Its giving random output each time i execute it.
Thread-0
Thread-1
MyThread1 running :: 1398752090142
MyThread2 running :: 1398752090142
next time
MyThread1 running :: 1398752090142
Thread-0
Thread-1
MyThread2 running :: 1398752090142
next time
Thread-0
MyThread1 running :: 1398752090142
Thread-1
MyThread2 running :: 1398752090142
Could anyone please explain why is it happening so?
Thanks.

It depends solely on the JVM Thread scheduler to schedule a thread. It may do it in any order when you have multiple threads. Hence you see different output.

When you start a thread, the started thread runs in parallel of all the already running threads. The thread scheduler dispatches the various threads on the available processors, and each thread gets some processor time, each in its turn. But the processor, the order and the time assigned to each thread is up to the OS thread scheduler, and you have absolutely no guarantee.

This is actually pretty expected behavior for multiple threads like this. The reason is that when you have multiple threads you can make no assumptions about the order or speed at which they run, no matter if you're running them on a multicore/threaded processor or not.
In the case that you're on a processor that only supports a single thread at a time, the order/time that threads will run is dependent entirely on how the JVM schedules your threads. Because it can schedule the threads however it wants and for as long as it wants you'll have some threads reaching their print calls earlier than others.
In the case that you're on a process that allows concurrent running of threads, you'll essentially get a race condition between various threads as to which one reaches the print statement first.

Related

Spring Java #Scheduling configuration

Using #Scheduling to run method at #Scheduled(fixedRate = 10000) and set up #Scheduling threading by implementing SchedulingConfigurer
#Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(10);
}
if I used Thread.sleep or Lock , no other thread is created by Executor unless Thread.sleep wake up or lock is cleared.
Can someone explain internal working if i have 10 pool size they 10 threads should be created at rate of 10000 millisec.
Basically such behavior comes from ScheduledExecutorService implementation which is used internally by spring. If you will run this code you will notice the same behavior:
public static void main(String[] args) throws Exception {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
executor.schedule(() -> {
System.out.println("Running task in thread " + Thread.currentThread().getId());
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
System.out.println("interrupted while sleeping");
}
}, 1000, TimeUnit.MILLISECONDS);
Thread.sleep(10000);
executor.shutdownNow();
}
When you submit task to scheduled thread pool it is wrapped with RunnableScheduledFuture which is passed to delayedExecute method. This method adds the task to the tasks queue and starts new worker if current number of workers is less than corePoolSize. Worker tries to get a task from the queue and process it invoking run method. There is a dedicated DelayedWorkQueue implementation which returns tasks only if they are ready for execution. Here is how run method of RunnableScheduledFuture looks like:
/**
* Overrides FutureTask version so as to reset/requeue if periodic.
*/
public void run() {
boolean periodic = isPeriodic();
if (!canRunInCurrentRunState(periodic))
cancel(false);
else if (!periodic)
ScheduledFutureTask.super.run();
else if (ScheduledFutureTask.super.runAndReset()) {
setNextRunTime();
reExecutePeriodic(outerTask);
}
}
As you can see it invokes actual task logic in runAndReset, calculates the next running time and submits the same updated task to the queue again (reExecutePeriodic is almost the same as schedule). There is only a single periodic task for all executions which is resubmitted again and again with updated time after the previous execution is finished. So such thread pool runs only a single instance of each task type in any given moment and scales only for different type of tasks.
If you are interesting in how spring schedules tasks take a look at ScheduledTaskRegistrar class and particularly at scheduleFixedDelayTask method.
In the case that you use threadpool:
By default you going to have 10 threads in your pool(already initialized). The first time that #scheduled is executed, this function is going to execute in a thread from your pool (now remaining 9 threads), if the function yet finished and #scheduled is executed again, your function going to executed in other thread from you your pool, so now you have 8 thread remaining in your pool. (8 idle, 2 running threads)
If you aren`t use threadpool only one thread is used.
spring documentation:
If you do not provide a 'pool-size' attribute, the default thread pool
will only have a single thread. There are no other configuration
options for the scheduler.
https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/html/scheduling.html

Why this concurrent execution always give me the same trace?

I'm trying to understand concurrent execution in Java, but given this code :
class Inter extends Thread {
public void run() {
System.out.println("Starting...");
try {
sleep(10000);
} catch (InterruptedException e) {
System.out.println("Interrupted."); }
System.out.println("Finished.");
}
public static void main(String[] args) {
Inter hi = new Inter();
hi.start();
System.out.println("Sending interruption...");
hi.interrupt();
System.out.println("Sent.");
}
}
I don't know why always give me this trace :
Sending interruption...
Sent.
Starting...
Interrupted.
Finished.
No matter how many times I run :
$ java Inter
As fars as I know in Java, when we execute the start() method in a new thread, the execution of this thread starts.
So , since the main thread and the Inter thread are concurrently executed, why can't be this a possible trace, ?
Starting..
Sending interruption..
Sent
Interrupted
Finished
So, since the main thread and the Inter thread are concurrently executed, why can't be this a possible trace?
Yes, it can. If you run your program a thousand times, most probably you will have that output at least once.
It's up to the operating system thread scheduler to arrange the threads execution in order to give that possible output, but we have no control over the scheduler. Hence, the importance of properly designing your code to prevent race conditions.

State of thread while in run() method (Java)

I am trying to understand multithreading in java. As I was going through the various states a Java thread can be in (new, Runnable, Running, Waiting/Blocked, Dead). I tried to run some simple code to check the states of the thread.
I created a class MyThread that extends Thread and overrode run() method.
package com.practice.threads;
public class MyThread extends Thread {
#Override
public void run() {
super.run();
System.out.println("Running Mythread.");
System.out.println("State of thread : " + this.getState()); // line 2
}
}
Now I have created a simple class to test the states of thread :
package com.practice.threads;
public class ThreadStateDemo {
/**
* #param args
*/
public static void main(String[] args) {
MyThread myThread = new MyThread();
System.out.println("State of thread : " + myThread.getState()); // line 1
myThread.start();
}
}
Running this class give the following output :
State of thread : NEW
Running Mythread.
State of thread : RUNNABLE
The output of line 2 is something I don't understand. When run() method of a thread instance is being executed, how can it be in RUNNABLE state? I saw mention of a RUNNING state in a book (SCJP Suncertified Programmer). Should it not show RUNNING?
The book has an (easy-to-make) error, the state is RUNNABLE, not RUNNING. There is no RUNNING state, see the JavaDoc:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
(My emphasis)
It's just an odd, slightly pedantic name, since technically, it's only running if the OS is running it. But it's "running" from the JVM's point of view.
The JVM doesn't control whether the thread is running or not, the OS does. The JVM only knows if it asked the OS to run the thread which is what makes it RUNNABLE.

Deamon thread not working T1,T2,T3 are the classes. I wrote separately. What mistake did I make? Why is my deamon thread not reachable?

My code:
package multithreading;
public class JoinT1T2T3 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon thread is running");
}
else
{
System.out.println("Slave thread");
}
}
public static void main(String args[])
{
Thread t=new Thread();
t.setDaemon(true);
T1 thread1=new T1();
T2 thread2=new T2();
T3 thread3=new T3();
System.out.println("First Thread name is::: "+thread1.getName());
thread1.setName("XXXXXXXXXX");
System.out.println("First Thread After changing name::: "+thread1.getName());
System.out.println("First thread's id is :::"+thread1.getId());
thread1.start();
try
{
thread1.join(3000);
}
catch(Exception e)
{
System.out.println("-----------");
}
//thread2.start();
thread2.start();
thread3.start();
}
}
Why is my daemon not reachable? Please provide me an explanation and code.
T1,T2,T3 are three different classes. The main method is also the run method. I created a new thread instance. Still getting "code not reachable". Which is if{} else{} in run method.
You are getting the "not reachable" error because JoinT1T2T3#run() is never called anywhere.
To Reach JoinT1T2T3#run()
In order for a run() method to be called, an object of its containing class should be explicitly passed to a Thread at construction-time using Thread#(Runnable). For example:
Thread t = new Thread(new JoinT1T2T3());
Now, Thread t will call JoinT1T2T3#run() whenever it starts.
To Run t
Even if t is a daemon, it must still be start()'ed just like any other Thread, or else it will not run. (and thus JoinT1T2T3#run() will never be called) So you need to do this:
Thread t = new Thread(new JoinT1T2T3());
t.setDaemon(true);
t.start();
explaining "daemon" threads
Generally speaking, in Java the only functional difference between a deamon Thread and a non-daemon Thread is that "the Java Virtual Machine exits when the only threads running are all daemon threads" (source). Other than that, a daemon Thread behaves exactly like a non-daemon Thread, syntax and all. It must still be constructed with a Runnable and start()'ed, just like any other Thread.
However, because a daemon thread may be abruptly terminated when the JVM exits, daemons should be used sparingly. In particular, daemons should not be used for any I/O or resource cleanup. "Normal" guarantees about stuff like finally blocks and stack unwinding don't necessarily apply to daemon threads--if the JVM decides to exit, all daemons are immediately abandoned. (source)
Java daemons should be used only for background housekeeping, bookkeeping, metrics, non-critical monitoring, etc.

Java Runnables start running before they are called

I have a function whose output is processed by multiple threads (created after the function call occurs). But when I run the program I receive a NullPointerException from the thread before the function is finished running. How do I specify for Java not to start the threads early?
public class MainThread extends Thread {
public MainClass() {
...
myRunnable1 = new myRunnable(args[]);
myRunnable2 = new myRunnable(args[]);
...
}
public void run() {
for (someNumberOfRuns) {
function1();
System.out.println("Done");
thread1 = new Thread(myRunnable);
thread2 = new Thread(myRunnable);
thread1.start();
thread2.start();
...
}
}
}
On the first iteration through the for loop, both thread1 and thread2 will throw NullPointException errors, then the system will print out "Done". Does anyone know why the two threads are starting before their respective start() calls in the method?
Thanks.
(Java version is 1.6u26)
Does anyone know why the two threads are starting before their respective start() calls in the method?
This does not happen under Java -- if the thread is being started then some code is starting it. I suspect that you are either calling the run() method directly in the thread that instantiates MainThread or you are calling start() in some place that you aren't expecting.
It may help if you use a debugger and put a breakpoint in the run() method to see who is calling it. If you want to use println debugging you could print out an exception that shows the stack trace inside of run():
new Throwable().printStackTrace();
If you provide the code that actually instantiates the MainThread we may be able to help you more.
If you are asking how to make a bunch of threads all wait to be started at the same time,
Have each thread execute a Runnable, and have the first line of run() be
barrier.await(LONG_TIMEOUT_MS, TimeUnit.MILLISECONDS);
where barrier is defined as
final CyclicBarrier barrier = new CyclicBarrier(numThreads + 1);
Then when you're ready for all of them to start, call
// Wait for all threads to be ready, then start them all at once
barrier.await(LONG_TIMEOUT_MS, TimeUnit.MILLISECONDS);
A timeout indicates that one of your threads did not execute withing the given time.

Categories