Java threads and synchronized blocks

我只是一个虾纸丫 提交于 2019-12-04 19:13:38

问题


Suppose I'm executing a synchronized block of code inside some thread and within the synchronized block I call a method that spawns another thread to process a synchronized block of code that requires the same lock as the first method. So in pseudo Java code:

public void someMethod() {
  synchronized(lock_obj) {
    // a whole bunch of stuff...

    // this is the last statement in the block
    (new Thread(someOtherMethod())).start();
  }
    // some more code that doesn't require a lock
}

public void someOtherMethod() {
  // some setup code that doesn't require a lock

  // return the stuff we want to run in another thread
  // that does require a lock
  return new Runnable() {
    @Override
    public void run() {
      synchronized(lock_obj) {
        // some more code
      }
    }
  };
}

I have no idea how to make sense of that code. Is what I have written even legal? Syntactically I don't see any issues but I'm not sure how to reason through code like that. So when I execute someOtherMethod() in order to create an instance of Runnable in what kind of scope does the code before the return statement run? Does it execute as part of the first synchronized block? Assume there are some other threads working as well that might require the lock on lock_obj.


回答1:


You are still holding the lock during the creation of runnable and the thread, but after you call start and before the thread actually picks up you are relinquishing the lock. The new thread will have to compete for the lock with other threads.




回答2:


There's nothing wrong about this code. Before the return statement in someOtherMethod(), the code is running in the synchronized block of someMethod(). After the new thread starts, it will block on the synchronized statement inside the run() method until it obtains a lock on lock_obj (at the earliest, whenever someMethod() exits its synchronized block).




回答3:


If someMethod() is invoked first, its the classical example of a deadlock.

Is what I have written even legal?
---- Yes it is perfectly legal syntactically.

So when I execute someOtherMethod() in order to create an instance of Runnable in what kind of scope does the code before the return statement run? ----If the someOtherMethod() is invoked from within someMethod() then its in scope of the synchronized block of the someMethod() method.



来源:https://stackoverflow.com/questions/5295065/java-threads-and-synchronized-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!