After reading throw Daemon threads and implementing according to my requirements raised several doubts.
Please clarify me
I am using ServletContextListener class to invoke a Daemon thread which needs to run unitl JVM exits
public void contextInitialized (ServletContextEvent event) {
context = event.getServletContext();
//getting from spring context
MyServiceManager serviceManager = (MyServiceManager) ctx.getBean("myServiceManager");
serviceManager.setDaemon(true);
serviceManager.start();
}
in ServiceManager class I am running an infinite loop to run the program foever until JVM exists
public void run() {
try {
startService();
} catch (Exception e) {
logger.error("Error Occured in Background Process Runner");
}
}
private void startService(){
while(true){
try{
//invoke some new threads and do processing jobs until server/jvm stops
}catch(Exception e) {
//log but don't quit
}
}
}
}
The concern is, will daemon thread with the above implmentation runs foever? if not, what should i do to achieve my job. Unless JVM stops (server stopped), tell it to not to quit.
Note: I am trying my level best to format this post. but today something is going, it's not getting formatted :(
Your daemon thread will run until the run() method terminates, either by exiting normally or by throwing an exception (or until the VM exits, which is what you want). Since you catch all exceptions thrown by startService(), it will run until startService() returns or throws an exception, and will then exit normally.
Be aware that if startService() is interrupted while it is waiting for I/O, sleeping, or in a wait state, then it will generally throw an InterruptedException. Well-behaved threads usually exit when they are interrupted, as this is the normal method for telling a thread to exit.
Note that marking the thread as a daemon only means that the VM will not wait until the thread exits before it shuts down. None of the other behavior regarding thread termination is affected by the thread being a daemon or not.
Related
In service code, I have a ScheduledTaskExecutor that starts a job, then a second thread that will cancel that first thread by interrupting it. The job checks for interrupts intermittently, and when the job gets one, it will throw an InterruptException; the service has a try/catch around that job and the catch handles that interruption. My problem is, the catch block is never hit. The job is definitely being interrupted, clear from logging statements on the job side, Once it throws the InterruptException, it's lost and the service can't catch it.
I tried changing Thread.interrupted() to Thread.currentThread().interrupted(), but it didn't fix the problem.
Here's the server-side code that waits for the InterruptException from the job. The interrupt signal is sent to thread via another thread that's scheduled to run after a timeout. I've verified the job does get the interrupt signal.
private void run() {
try {
job.run();
} catch (InterruptedException e) {
log.info("Job was interrupted", e);
} finally {
duration.stop();
timer.record(duration);
}
}
Here's how the job checks for interrupts:
public void checkForInterrupt() throws InterruptedException {
if (Thread.currentThread().isInterrupted()) {
logger.info(jobName + " was interrupted");
throw new InterruptedException(jobName + " has been interrupted");
}
}
I'm expecting to see this log line log.info("Job was interrupted", e);
The last thing I hear from the thread is a log statement that confirms it's interrupt flag has been set, after which it throws the InterruptedException.
The job is definitely being interrupted, clear from logging statements on the job side, Once it throws the InterruptException, it's lost and the service can't catch it.
This is a FAQ. Whenever the InterruptedException is thrown, the interrupt flag on the thread is cleared. If you need the thread to be stilled interrupted, you need to re-interrupt it. That is always the correct pattern when catching InterruptedException. The reason for it is that if you are writing some sort of library, you don't want to swallow the interrupt flag which would mean that the caller won't know if a thread was interrupted. Interrupting a thread is designed as a graceful shutdown (as opposed to the deprecated stop() method). So propagating the interrupt thread is always a good pattern.
For example:
...
} catch (InterruptedException e) {
// we always should re-interrupt the thread when we catch InterruptedException
Thread.currentThread().interrupt();
log.info("Job was interrupted", e);
Then when you get back to the caller you can test the interrupt flag:
if (Thread.currentThread().isInterrupted()) {
...
If you want a lot more detailed information about the various methods that throw InterruptedException and the various Thread methods that affect the flag, then see my answer: Methods that Clear the Thread.interrupt() flag
For example, folks should never use Thread.interrupted() because that clears the interrupt flag when it tests it. Your use of Thread.currentThread().isInterrupted() is correct.
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.
I'm developing a multithreaded application to make connections to external servers - each on separate threads - and will be blocked until there is input. Each of these extends the Thread class. For the sake of explanation, let's call these "connection threads".
All these connection threads are stored in a concurrent hashmap.
Then, I allow RESTful web services method call to cancel any of the threads. (I'm using Grizzly/Jersey, so each call is a thread on its own.)
I retrieve the specific connection thread (from the hashmap) and call the interrupt() method on it.
So, here is the question, within the connection thread, how do I catch the InterruptedException? (I'd like to do something when the connection thread is stopped by an external RESTful command.)
So, here is the question, within the connection thread, how do I catch
the InterruptedException?
You can not. Since if your thread is blocked on a read I/O operation it can not be interrupted. This is because the interrupt just sets a flag to indicate that the thread has been interrupted. But if your thread has been blocked for I/O it will not see the flag.
The proper way for this is to close the underlying socket (that the thread is blocked to), then catch the exception and propagate it up.
So since your connection threads extend Thread do the following:
#Override
public void interrupt(){
try{
socket.close();
}
finally{
super.interrupt();
}
}
This way it is possible to interrupt a thread blocked on the I/O.
Then in your run method do:
#Override
public void run(){
while(!Thread.currentThread().isInterrupted()){
//Do your work
}
}
So in your case don't try to catch an InterruptedException. You can not interrupt the thread blocked on I/O. Just check if your thread has been interrupted and facilitate the interruption by closing the stream.
When you call Thread.interrupt() on some thread, what happens is that 'interruption' flag is set for that thread. Some methods do check this flag (by Thread.interrupted() or Thread.isInterrupted()) and throw InterruptedException, but usually only methods that can block do that. So there is no guarantee that InterruptedException will ever be thrown in interrupted thread. If you don't call any method that throws InterruptedException, there is no point in catching that exception, since it will not be thrown at all. However you can always check if your thread was interrupted by calling Thread.isInterrupted().
the problem it is with blocking.
Hoverer, try this code, maybe it will help you:
try{
yourObject.read();
}catch(InterruptedException ie){
// interrupted by other thread
}
catch(Exception ex){
// io or some other exception happent
}
your read method, should check if there is available buytes at socket for eg, if there are than read it, othervise go to speel mode. When is sleeping than is available the wake up (InterruptedException) at pur socket read ( whatever read have you) it will be blocked. Some API has a value to max waiting, eg 5 sec 60 sec, if nothing o read than it will be next code executed.
class MyReadingObject
{
public read() throws InterruptedException{
while(shouldIread){
if(socket.available() > 0){
byte[] buff = new byte[socket.avaialble()]
socket.read(buff);
return;
}
else{
Thread.currentThread.sleep(whateverMilliseconds);
}
}
}
}
something like that, but with error handling and some design patterns
Calling interrupt() on a thread doesn't stop it, it just switches on the interrupt flag. It's the responsibility of the code to handle the change in the interrupt status of the thread in consideration and act accordingly. If you are performing a blocking operation in that thread, you are pretty much SOL because your thread is "blocking" on the read. Have a look at the answer which I posted here. So basically, unless you are looping over stuff or periodically checking some flags inside that thread, you have no way of breaking out without closing sockets or stuff like that.
One solution here is to "explicitly" expose the underlying connection object and call close() on it, forcing it to throw some sort of exception, which can be then handled in the threaded code. Something like:
class MyAction extends Thread implements Disposable {
public void doStuff() {
try {
byte[] data = this.connection.readFully();
} catch (InterruptedException e) {
// possibly interrupted by forceful connection close
}
#Override
public void dispose() {
this.connection.close();
}
}
// Elsewhere in code
MyAction action = conMap.get("something");
action.dispose();
Use a try-catch like so:
try {
//code
} catch ( InterruptedException e) {
//interrupted
}
I think that should do the trick, you could also keep a boolean variable on whether to exit, so they would check that variable, if it's true, stop
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.
I am running a thread whose main action is to call on a proxy using a blocking function , and wait for it to give it something.
I've used the known pattern of a volatile boolean and the Interruption , but I'm not sure it will work: When I tried to add a catch block for InterruptedException , I get the error:
Unreachable catch block for InterruptedException. This exception is never thrown from the try statement body
So if I'm never going to get anInterruptedException, this means I'll never get out of the blocking action - thus will never stop.
I'm a bit puzzled. Any idea?
public void run() {
Proxy proxy = ProxyFactory.generateProxy();
Source source;
while (!isStopped) {
try {
source = proxy.getPendingSources();
scheduleSource(source);
} catch (Exception e) {
log.error("UnExpected Exception caught while running",e);
}
}
}
public void stop() {
this.isStopped = true;
Thread.currentThread().interrupt();
}
First, you don't really need a separate flag (if you do, use an AtomicBoolean), just check Thread.currentThread().isInterrupted() as your while condition.
Second, your stop method won't work because it won't interrupt the correct thread. If another thread calls stop, the code uses Thread.currentThread() which means the calling thread will be interrupted, not the running one.
Finally, what is the blocking method? Is it scheduleSource()? If that method doesn't throw InterruptedException, you won't be able to catch it.
Try the following:
private final AtomicReference<Thread> currentThread = new AtomicReference<Thread>();
public void run() {
Proxy proxy = ProxyFactory.generateProxy();
Source source;
currentThread.set(Thread.currentThread());
while (!Thread.currentThread().isInterrupted()) {
try {
source = proxy.getPendingSources();
scheduleSource(source);
} catch (Exception e) {
log.error("UnExpected Exception caught while running", e);
}
}
}
public void stop() {
currentThread.get().interrupt();
}
Only a few, well-defined "blocking methods" are interruptible. If a thread is interrupted, a flag is set, but nothing else will happen until the thread reaches one of these well-defined interruption points.
For example, read() and write() calls are interruptible if they are invoked on streams created with a InterruptibleChannel. If a Socket is used as the starting point, calling interrupt() on a Thread blocked in the read has no effect. Note that if a blocking I/O operation is interrupted successfully, the underlying channel is closed.
Another large class of interruptible operations are those thrown by various blocking operations on classes in the java.util.concurrent packages. Of course, the original wait() method is interruptible as well.
Blocking methods can be identified by looking for a throws InterruptedException in their method signatures. They should be well-documented too, to describe any side-effects of interruption.
You can write an interruptible method of your own, but it has to be composed of interruptible lower-level operations itself.
ok, people, don't kill me over this.
I experimented with Thread.stop() for fun, to kick thread out of a blocking action, catch ThreadDeath, keep target thread alive, and move on.
It seems working. The world isn't ending. But I'm just saying. You are responsible for you own doing. Why am I rapping?
You stop method is calling interrupt on the wrong thread. Thread.currentThread() is the thread that is interrupting, not being interrupted.
How are you calling stop from the executing thread?
If you call stop() from another thread, you'll kill it, not the thread running in the try/catch block.