Вопрос

I need to shutdown alot of differently implemented threads which only have some Shutdown interface in common. I don't want to pass some global collection through the entire code and add newly created threads manually, because it is guaranteed to be forgotten somewhere and therefore is a bug hazzard.

Is there some neat way, maybe through reflection tricks, to grab all instances of some interface? Or is there alternativly some way to force newly created threads to register with the collection? I can only think of using some kind of super constructor and then passing the this reference, but this is extremly bad style.

This kind of task is like logging, some meta stuff that shouldn't live on the same level as the rest of the business logic.

Is there a standard shutdown registration pattern or some best practise?

P.S. All code fragments can be edited.

Это было полезно?

Решение

A brute force approach would be to list all running threads and simply use:

if(thread instanceof Shutdown) {
  ((Shutdown)thread).shutdown();
}

Of course there are more elegant approaches:

  • Use DI to inject the global thread container

  • Consider using ThreadFactory with some custom logic.

Другие советы

If you are open to some aspect oriented programming then you can accomplish this pretty easily using Aspect J.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top