4

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
  • Are all the implementations part of your project or might they come from other jars at runtime? – Affe Jan 06 '12 at 20:25
  • The parts are from a few projects, but I can edit all of them, therefore it might as well be one project. – Franz Kafka Jan 06 '12 at 20:26

2 Answers2

4

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.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • I think a factory will be the easiest way. But I am wondering if it is a bad idea to let the Factory only have static methods but at the same time keep a static Collection of created Threads? Then I could easly poll and add new Thread without having to pass references. But I always feel a bit uncomfortable having state in a static class. – Franz Kafka Jan 07 '12 at 01:29
1

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

Perception
  • 79,279
  • 19
  • 185
  • 195
  • It's a different compiler and then I can use some annotations to get this working. Or what would be the general approach? Its the first time I've heard of Aspect J. – Franz Kafka Jan 06 '12 at 22:59