Search code examples
javamultithreadingjvmclassloader

Thread creation listener


Is it possible to write Thread creation listener in java? For example using aop?!

I mean something like this that if my application creates a thread I would like to register this object in my own table, container or something.


Solution

  • I think this would be possible with AOP (aspectj for instance). But it is still required to create your own Thread and ThreadGroup/Executor types, unless you can recompile the JDK classes with the aspect compiler. Define the pointcut on your thread's start method if you want to register on thread launching or on the createThread of your pool if you want to register on the creation of the thread objects.


    The following works only if you recompiled the JDK with the aspect compiler: All threads are started with Thread.start, so write a pointcut for that method then you can use advices to do what you'd like to. Of course this is not perfect since e.g. a cachedThreadPool executor might not start a new thread for each task, but maybe if you register a pointcut on Runnable.run and Callable.call rather than on Thread.start, that might be sufficient enough.