Java Runnables start running before they are called - java

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.

Related

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.

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.

Is the Thread really stop when I use new Thread().interrupt();?

I create a Thread like the following code. This Thread will send the POST request.(The code is not yet written , so I didn't post the detail code of Thread )
final Runnable Update_Value = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
**// It will send the POST request to the Server**
}
};
I use the new Thread(Update_Value).start(); to run the Thread.
And I use new Thread(Update_Value).interrupt(); to interrupt the Thread.
1. If I use new Thread(Update_Value).start(); to run the Thread.
2 How to interrupt the Thread when I using new Thread(Update_Value).start(); ?
3 Is the thread close when App close if I didn't close it ?
Sorry about my English...Thanks in advance.
If you use new Thread each time, the two calls create two different threads; they don't act on the same thread.
The interrupt() method does not stop the thread. Rather, it tells the thread to take a look at any interrupt flags that may also have been set, such as a shutdown flag. The thread itself must contain code to check for interrupts and to check for flags such as shutdown flags.
interrupt method is used to send an interrupt signal to a running thread. Calling on a new thread does not make sense.
To properly handle the interrupt signal, your thread code should catch InterruptedException. Something like this:
try {
// do thread task
} catch (InterruptedException e) {
// interrupted: if required do something on interrupt or simply return
return;
}

IntelliJ Thread Debug

Does IntelliJ IDEA provide thread-debugging? That is - Netbeans allows you to debug multiple threads, and halting at those breakpoints (automatically). However all I seem to be getting in IntelliJ is "thread dumping", which seems to be an analysis that is manual, and a snapshot taken when I clicked 'Thread Dump'.
Is there something I'm missing?
I have google'd and not found sufficient information to assist.
I think you can. I have suspended threads via breakpoints by setting the suspend policy. This will suspend the thread that is executing this piece of code. If you have multiple thread then I would think they would carry on.
To quote the suspend policy
Item Description
All : When the breakpoint is hit, all threads are suspended
Thread : When the breakpoint is hit, the thread where the breakpoint is hit is suspended.
None: No thread is suspended.
You have a nice Threads view available.
Press the little gearwheel and you will see all active threads.
And on each breakpoint you can set the Suspend Policy. You can either make the Thread alternative the default for all breakpoints or you can set them individually on each breakpoint.
For me the problem with not accessing thread still occcurs. I set up brakepoints to all. And put brakepoints inside calling methods. What I noticed is that the method in new thread is beeing accessed when i call run() but not start(). Just wondering why, AFAIK the start() method should call run(). Nevertheless, the output from thread occurs even I call .start(), but never access it.
For me the issue was that there seems to be a race condition with resuming threads after breakpoints and evaluating breakpoints in IntelliJ.
My short-term work around was to not set Breakpoints right before I spawn a thread. If I don't do this the first few Breakpoints in the run() or call() are missed.
I think the problem you have is that the child threads are being closed sooner than you expected because the main thread(the test itself) reaches to the end.
Remember that when you do a Thread.start() an asynchronous call starts, then if you are running your tests using Junit the execution will continue after this call until the end of the test, and as soon as it reaches to the end, it shutdowns the threads you started inside it.
Therefore, if you have something like:
01. import org.junit.Assert;
02. import org.junit.Test;
03. public class ThreadTest {
04. static boolean didIGetIt = false;
05. #Test
06. public void testThread() {
07. Thread myThread = new Thread(new Runnable() {
08. #Override
09. public void run() {
10. System.out.println("I am an asynchronous task");
11. System.out.println("and JUnit won't wait for me to finish my job!");
12. didIGetIt = true;
13. }
14. });
15. myThread.start();
16. Assert.assertTrue(didIGetIt);
17. }
18. }
It will execute the Assert before the code inside the run() leading to a fail test.
But if you add a simple sleep you could stop the main thread and debug and do what you need before the main thread stops.
01. import org.junit.Assert;
02. import org.junit.Test;
03. public class ThreadTest {
04. static boolean didIGetIt = false;
05. #Test
06. public void testThread() throws InterruptedException {
07. Thread myThread = new Thread(new Runnable() {
08. #Override
09. public void run() {
10. System.out.println("I am an asynchronous task");
11. System.out.println("and JUnit won't wait for me to finish my job!");
12. didIGetIt = true;
13. }
14. });
15. myThread.start();
16. System.out.println("Let's wait for child threads to finish");
17. Thread.sleep(5000);
18. Assert.assertTrue(didIGetIt);
19. }
20. }
Surely there are better ways to do it, but the Thread.sleep may be what you are looking for.
Hope it may help somebody!

How to keep my program alive for as long a daemon thread is running?

I have a requirement, that I want to start a poller once which will run foreever until the machine is restarted or the process is being killed. Now, I tried to start the poller from a main method using a shell script, but the problem is that as soon as the main method completed its execution, the poller also stoped working, as i am not using any servers to achieve so.
I heard something about daemon threads, but I am wondering how to create a daemon thread, which will run forever, and help my poller to run also.
UPDATE:
public class SomeThread extends Thread {
#Override
public void run() {
UnitPoller unitPoller = new UnitPoller();
unitPoller.doPolling();
}
public static void main(String[] args) {
SomeThread someThread = new SomeThread();
someThread.setDaemon(true);
someThread.start();
}
}
Above is my updated class, now whenever I execute this thread from the main method, it creates a thread but as soon as the execution of main method completes, my poller stops working, as the JVM shuts down.
With this problem, what should i do.
Thanks
You just create a thread and call th.setDaemon(true) before calling th.start().
Edit:
The above answers the question "how to create a daemon thread", but (as the scope of the question has changed), a proper answer would be: don't create a daemon thread if you want your thread to keep the JVM from exiting once the main thread completed.
1) You need someThread.setDaemon(false) instead of 'true'. A daemon thread actualy does NOT stop java from shutting down.
From the javadoc:
void java.lang.Thread.setDaemon(boolean on)
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
This method must be called before the thread is started.
2) I think it's not your main, but your run() method that finishes to soon. Try to put a while (true) loop around your doPolling method.
#Override
public void run() {
UnitPoller unitPoller = new UnitPoller();
while (true)
unitPoller.doPolling();
}
3) It's cleaner to call join() inside the main then to rely on daemon thread behavior.
try {
someThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
4) If you need a clean way to shut down the deamonthread. Consider implementing InterruptedException to exit the polling task. You can also use the shutdown hook.
The term "daemon thread" in Java is a bit misleading, as it really means "that thread is not supposed to keep the JVM alive". This means that the JVM will shut down as soon as the last non-daemon thread terminated (as you already stated in your question).
What you are possibly looking for is the Apache Commons Daemon project, which allows to create nice "system services", started through /etc/init.d/ entries and all. This works on Windows and *nix systems.

Categories