Reputation: 400
I am trying to track to obtain the parent thread id of each new thread created in a program using AspectJ. Since a new thread starts execution using the start() method, I thought the following technique should work:
aspect getParentThread {
pointcut threadStarting(): call(public void start());
Object around(): threadStarting() {
long parentThread = Thread.currentThread().getId();
Object ret = proceed();
long newThread = Thread.currentThread().getId();
if (parentThread != newThread) {
/*Store parentThread id in data structure */
}
return ret;
}
}
But this simply does not work. Although the advice executes, even after proceed() completes there is just a single thread id. So what am I getting wrong here?
Upvotes: 0
Views: 1298
Reputation: 67417
Warren Dew is right, but I want to add some sample code in order to show how you can easily do it with AspectJ. You do not even need an around()
advice, a simple before()
is enough.
Driver application:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
new Thread(
new Runnable() {
@Override
public void run() {}
},
"first thread"
).start();
new Thread(
new Runnable() {
@Override
public void run() {}
},
"second thread"
).start();
}
}
Aspect:
package de.scrum_master.aspect;
public aspect ThreadStartInterceptor {
before(Thread childThread) :
call(public void Thread+.start()) &&
target(childThread)
{
System.out.printf(
"%s%n Parent thread: %3d -> %s%n Child thread: %3d -> %s%n",
thisJoinPoint,
Thread.currentThread().getId(),
Thread.currentThread().getName(),
childThread.getId(),
childThread.getName()
);
}
}
Thread+
, i.e. to Thread
and subclass instances. I am doing this explicitly even though it is not strictly necessary because the next point already does it implicitly:Console log:
call(void java.lang.Thread.start())
Parent thread: 1 -> main
Child thread: 11 -> first thread
call(void java.lang.Thread.start())
Parent thread: 1 -> main
Child thread: 12 -> second thread
Upvotes: 2
Reputation: 8938
The issue is that all of your code executes in the parent thread, including the code after the child thread starts, because the start()
method is called from and executes in the parent thread.
You could try getting the ID of the new thread from the Thread
object on which the start()
method is called.
Upvotes: 1