Synchronized method in android
Asked Answered
H

2

17

You might think that this question is duplicate of this one but no answers of that question helps me for understanding synchronized method in android. I searched a lot on google for understanding synchronized methods and i found some answer but they didn't help me to perfectly understand Synchronized methods because no answer has any perfect practical example.

I have tried to understand synchronized method by implement 2 synchronized methods in my code and executing them concurrently but i am failed in properly implementing them. So, please provide explanation of synchronized method with simple example so, others like me also can understand it simply and in a faster way.

UPDATE

I am not sure i am going in right direction or not but i have tried following code which have 2 synchronized methods.

synchronized void add() {
    counter++;
    Log.e("JK", String.valueOf(counter));
}

synchronized void minus() {
    counter--;
    Log.e("JK", String.valueOf(counter));
}

and i have called this methods in two different threads using below code.

new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    synchronized (counter++) {
                        add();
                    }
                }
            },500);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    minus();
                }
            },1000);
Heather answered 10/10, 2018 at 10:54 Comment(4)
Please reduce your code to minimal possible example that reproduces your problem and post it. You are now asking us to explaing the whole concept of synchronization and it is, without changes, eligible to be closed as "too broad."Showmanship
okay...let me post my code. @ShowmanshipHeather
@Showmanship please take a look at updated question.Heather
Usage of synchronized (counter++) {add();} is incorrect, the method add is already synchronized, no need to put it in synchronized block in runnable. Also, counter seems to be shared resource, which you don't want to be accessed from 2 threads simultanously. This means you should change it ONLY from synchronized methodsShrubby
S
49

Synchronized method is a method which can be used by only one thread at a time. Other threads will be waiting until the method will be released. You should have only serious reasons to declare method as synchronized because such method decreases the productivity. The classic case of synchronized method usage is when several threads are using same resources i.e. change state of some object and it is needed to make sure only one thread performs it at a time, otherwise it will cause inconsistency. Also make sure to make synchronized method as small as possible, ideally reduce it to contain only operations which can manipulate common resources.

For example the class Reporter has common resource fileWriter. It writes to file some messages with information about authors.

class Reporter{
    private FileWriter fileWriter;
    public synchronized void addRecord(String author, String message) throws IOException {
        fileWriter.write("\n<<<<<<<<<<>>>>>>>>>>\n");
        fileWriter.write("Message written by:" + author + "\n");
        fileWriter.write("Message content:" + message);
    }

    public Reporter(FileWriter fileWriter) {
        this.fileWriter = fileWriter;
    }
}

Suppose you are running this code from 2 different threads:

Reporter reporter = new Reporter("path/report");
...
Thread thread = new Thread(){
    public void run(){
      reporter.addRecord("John", "Hi");
    }
  }
 thread.start();
Thread thread2 = new Thread(){
    public void run(){
      reporter.addRecord("Bill", "Hello");
    }
  }
 thread2.start();

The result for synchronized method will be like this :

<<<<<<<<<<>>>>>>>>>>
Message written by:John
Message content:Hi
<<<<<<<<<<>>>>>>>>>>
Message written by:Bill
Message content:Hello

If method is not synchronized several threads may write to file simultanously, which can cause an unpredictable sequence in file, like this:

<<<<<<<<<<>>>>>>>>>>
<<<<<<<<<<>>>>>>>>>>
Message written by:John
Message written by:Bill
Message content:Hello
Message content:Hi
Shrubby answered 10/10, 2018 at 11:6 Comment(4)
Thanks for your valuable answer but it will be more better if you provide any example.Heather
@Jaydip example addedShrubby
yes you are right but how can i generate both cases output?Heather
updated answer with code running the synchronized method, to see the difference run same code with and without synchronized declarationShrubby
A
-1

Synchronized method is a method which can be used by only one thread at a time. Other threads will be waiting until the method will be released. You should have only valid reasons to declare method as synchronized because such method decreases the productivity and performance.

Autorotation answered 13/9, 2020 at 6:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.