Thread creation listener

前端 未结 3 560
灰色年华
灰色年华 2021-01-05 07:59

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

3条回答
  •  误落风尘
    2021-01-05 08:13

    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.

提交回复
热议问题