I have a question related but not identical to my first question:
Java: what happens when a new thread starts from a synchronized block?
Is it a common practice to create and start()new Threadwhen you hold a lock?
Will it smell like code?
Basically, I have a choice between this:
public synchronized void somemethod() {
(every time I find a callback to be notified I start a thread)
Thread t = new Thread( new Runnable() {
void run() {
notifySomeCallback();
}
}
t.start();
...
(lengthy stuff performed here, keeping the lock held)
...
}
or that:
public void somemethod() {
(create a list of callbacks to be notified)
synchronized(this){
(potentially add callbacks)
...
(lengthy stuff performed here, keeping the lock held)
...
}
(notify the callbacks without holding a lock and once
we know the lock has been released)
}
I think the latter is better, but I wanted to know if there are any cases where the first option would be okay? Do you sometimes do it? Did you see that?
source
share