Syncing by "this" or private object in Java?

Possible duplicate:
Avoid syncing (this) in Java?

What is the difference between the two parts of the code? What are the advantages and disadvantages of each?

1)

public class Example { private int value = 0; public int getNextValue() { synchronized (this) { return value++; } } } 

2)

 public class Example { private int value = 0; private final Object lock = new Object(); public int getNextValue() { synchronized (lock) { return value++; } } } 
+6
source share
4 answers

The main reason I would choose the second approach is because I do not control what clients do with instances of my class.

If for some reason someone decides to use an instance of my class as a lock, they will interfere with the synchronization logic in my class:

 class ClientCode { Example exampleInstance; void someMethod() { synchronized (exampleInstance) { //... } } } 

If in my Example class I use a lock that no one else sees, they cannot interfere with my logic and introduce an arbitrary mutex, as in the above scenario.

To summarize, this is just an application of the principle of information hiding.

+4
source

I would prefer the second option if I need to perform two different tasks at the same time, which are independent of each other.

eg:.

 public class Example { private int value = 0; private int new_value = 0; private final Object lock1 = new Object(); private final Object lock2 = new Object(); public int getNextValue() { synchronized (lock1) { return value++; } } public int getNextNewValue() { synchronized (lock2) { return new_value++; } } } 
+3
source

I would say that the second method is better. Consider the following situation:

 public class Abc{ private int someVariable; public class Xyz { //some method,synchronize on this } //some method, and again synchronize on this } 

In this situation, this not the same in the two methods. One of them is the inner class method. Therefore, it is better to use a shared object for synchronization. For example, synchronized (someVariable) .

0
source

I think it really depends on the situation. Suppose your class is a subclass and the superclass has a method that has synchronization. And let's say you work with the same data set and want to maintain integrity in your method. Then definitely approach 1 is what you should use.

Otherwise, the second approach will work better based on what Bones mentioned

0
source

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


All Articles