Daemon threads: Is it possible to change a running thread from user thread to daemon thread?

I'm using a 3rd party API at my system, and this API starts an user thread that runs forever. Once my program ends, the JVM keeps running because of that thread, so I've tried to get this thread reference and change it via

thread.setDaemon(true);

but it throws an IllegalThreadStateException, because the thread is active. I'm thinking about using reflection to change the daemon attribute on the thread class. Will it work? Is there another way I can achieve this?

Upvotes: 1

Views: 566

Answers (1)

MeBigFatGuy
MeBigFatGuy

Reputation: 28588

I'd suggest perhaps using something like aspectj to rewrite the byte code of the 3rdparty api to inject a setDaemon call in the code before the thread is started. Once the thread is started, most of the Thread methods are illegal, including setDaemon, as specified here http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setDaemon(boolean)

Upvotes: 1

Related Questions