Java: The usual practice of creating a new thread when blocking?

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?

+3
source share
3 answers

answer3:

  • . , , , , "" (, ).

  • , . , .

+4

, . , . , .

, , . , , .

? , , . , , , .

, . , , ( , ). , .

, Executor . .

+3

It depends on whether you want the callbacks to run simultaneously with long things or not. If we are talking about the Swing GUI, parameter 1 is not suitable because you should not perform Swing operations on multiple parallel threads, so I suggest the following:

public void somemethod() {   
   Thread t = new Thread( new Runnable() {
       void run() {
           synchronized(this) {
             doLengthyStuff();
           }
       }
    }
    t.start();

    (notify the callbacks)
}
+2
source

Source: https://habr.com/ru/post/1734520/


All Articles