Answer the question
In order to leave comments, you need to log in
Synchronized, code snippet lock or object lock?
Bruce Eckel, in "Java Philosophy" (complete edition) writes (p. 923)
When a task wishes to execute a piece of code guarded by the word synchronized, it checks, captures it, executes the code, and releases the lock., and then a little further on he writes that
to control access to a shared resource, you first place it inside an object.So what to use "code snippet" or object? Or should any shared resource (including a code fragment) be placed inside an object? Or is it possible to make just the method a shared resource without shoving it into an object? (for example, it was done in the code example on the next page, but then I don’t understand why he wrote to put the shared resource inside the object ) Please explain.
Answer the question
In order to leave comments, you need to log in
why did he write to put a shared resource inside an object
Or is it possible to make just the method a shared resource without shoving it into an object?
public void swap() {
synchronized (this)
{
//...логика метода
}
}
public synchronized void swap() {
}
}
public class Main {
private Object obj = new Object();
public void doSomething() {
//...какая-то логика, доступная для всех потоков
synchronized (obj) {
//логика, которая одновременно доступна только для одного потока
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question