I have 3 service classes(For now, suppose A, B, C). Each of them is a thread actually. In my requirement, each of them should have an infinite loop. But whenever I run a service class with infinite loop bean of other service classes are not created.
If there is no infinite loop, bean of each class is being created. Why is this happening?
Suppose it is Service A.
@Service
@Log4j2
public class A implements Runnable {
private boolean isRunning = true;
@Override
@PostConstruct
public void run() {
log.debug("A Thread Started!");
while (isRunning) {
// just a sleep for 2 sec
}
}
}
Suppose it is Service B.
@Service
@Log4j2
public class B implements Runnable {
private boolean isRunning = true;
@Override
@PostConstruct
public void run() {
log.debug("B Thread Started!");
while (isRunning) {
// just a sleep for 2 sec
}
}
}
Suppose it is Service C.
@Service
@Log4j2
public class C implements Runnable {
private boolean isRunning = true;
@Override
@PostConstruct
public void run() {
log.debug("C Thread Started!");
while (isRunning) {
// just a sleep for 2 sec
}
}
}
And this is my Main class:
@SpringBootApplication
@Log4j2
public class Main {
@Autowired
public ApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
@PostConstruct
public void createConnection() {
log.debug("Connecting to Server...");
// doing some staff
}
}
Now if I run like this, always got this log:
2020-07-14 21:21:52:129 [main] DEBUG support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'a'
2020-07-14 21:21:52:130 [main] DEBUG service.ProcessorService:27 - A Thread Started!
If I put any log in while loop of class A, then only those logs are shown.
If I comment on the loop portion of the class A and keep the class like this:
@Service
@Log4j2
public class A implements Runnable {
private boolean isRunning = true;
@Override
@PostConstruct
public void run() {
log.debug("A Thread Started!");
/* while (isRunning) {
// just a sleep for 2 sec
}*/
}
}
then got this in log:
2020-07-14 21:30:31:198 [main] DEBUG support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'a'
2020-07-14 21:30:31:199 [main] DEBUG service.ProcessorService:27 - A Thread Started!
2020-07-14 21:30:31:199 [main] DEBUG support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'b'
2020-07-14 21:30:31:199 [main] DEBUG service.ReceivingProcessingService:46 - B Thread Started!
If I comment on the loop portion of class B as well then only got each service class running. Can't understand the reason. Any help will be appreciated.