The following daemon-bean is running:
public class DaemonBean extends Thread {
private final static Logger log = LoggerFactory.getLogger(DaemonBean.class);
{
setDaemon(true);
start();
}
@Override
public void run() {
for(int i=0; i<10 && !isInterrupted(); ++i) {
log.info("Hearbeat {}", i);
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
It is daemon, so would terminate if singleton.
So, the following non-daemon bean is waiting for him:
public class Waitor1 extends Thread {
private final static Logger log = LoggerFactory.getLogger(Waitor1.class);
private Thread joinable;
{
setDaemon(false);
setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("Error in thread", e);
}
});
}
public Thread getJoinable() {
return joinable;
}
public void setJoinable(Thread value) {
this.joinable = value;
if( this.joinable != null ) {
start();
}
}
@Override
public void run() {
log.info("Waiting started");
try {
joinable.join();
} catch (InterruptedException e) {
log.info("Thread interrupted");
return;
}
log.info("Waiting ended");
}
}
The Spring configuration for beans is:
<bean id="daemon" class="beans.DaemonBean"/>
<bean id="waitor" class="beans.Waitor1">
<property name="joinable" ref="daemon"/>
</bean>
The question is: why is it working if runned from main and not working if ran from jUnit test?
Running code is
public static void main(String[] args) {
new ClassPathXmlApplicationContext("/beans/Waiting1.xml");
}
or
@Test
public void testWaiting1() {
new ClassPathXmlApplicationContext("/beans/Waiting1.xml");
}
In case of main I see all hearbeats. In case of jUnit I see only heartbeat 0, then message "Waiting started" and the program is terminated as if nobody waiting for non-daemon threads here.
What can be the reason of it?