1

I have a function in class A. I call this function from 3 parts of my application (in different activities).

This function does critical tasks in my app and because of that, I want it will be accessible just for one of these parts in my app(I mean that all 3 parts, can't call it at the same time)

I made the function like this:

   AnyType foobar(...) {
    synchronized(this) {
        doSomething();
    }
}

does synchronized guaranteed that no more than one request (from different classes ) at the time can execute the code of the function?

Because I call this function from different activities in my application, And in each place that I call this function I will make a new object of class A.

Ehsan
  • 2,676
  • 6
  • 29
  • 56

1 Answers1

1

does synchronized protect my function?

This is object level synchronization, which will allow only one thread to perform task on this object.

I will make a new object of class A

So, you will have different instances and your lock would be at instance level. So, assuming you created two instances of class A. So, two threads can work separately on this two objects.

You should avoid using synchronization on this object, instead you should create an Object and put lock on it. In your case, it is more likely to use Class level lock (static).

AnyType foobar(...) {
    synchronized(A.class) {
        doSomething();
    }
}
Ravi
  • 30,829
  • 42
  • 119
  • 173
  • so how can I protect this function? make this function static can help? – Ehsan Feb 13 '18 at 19:48
  • ```synchronized(A.class)``` will lock the whole of class A until ```doSomething();``` will be finished. am I right? – Ehsan Feb 13 '18 at 20:00
  • @Ehsan Not exactly. You need to understand that, object lock and class level lock are two different things. If thread hold object lock, then no other thread would able to access method until it gets same lock – Ravi Feb 13 '18 at 20:03
  • 1
    @Ehsan I would suggest to go through one of my old post https://stackoverflow.com/a/45657164/1162620 – Ravi Feb 13 '18 at 20:07
  • Thank you for this link, in the link you made the function synchronized, and I made a block synchronized in my function. is there any difference between these two way? – Ehsan Feb 14 '18 at 05:45
  • 1
    @Ehsan yes. synchronized block will reduce the scope of lock. – Ravi Feb 14 '18 at 06:20