I
I
iscateli2022-02-03 11:28:14
Java
iscateli, 2022-02-03 11:28:14

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

1 answer(s)
D
Dmitry Roo, 2022-02-03
@xez

why did he write to put a shared resource inside an object

Actually, in Java, all objects. You definitely can't do without them.
Or is it possible to make just the method a shared resource without shoving it into an object?

"These two spellings mean the same thing:"
public void swap() {

   synchronized (this)
   {
       //...логика метода
   }
}


public synchronized void swap() {

   }
}

synchronized always refers to some object. Either this , or with an explicit indication. For example:
public class Main {

   private Object obj = new Object();

   public void doSomething() {

       //...какая-то логика, доступная для всех потоков

       synchronized (obj) {

           //логика, которая одновременно доступна только для одного потока
       }
   }
}

based on Java's synchronized operator

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question