0 votes
in JAVA by
Why is synchronization necessary? Explain with the help of a relevant example.

1 Answer

0 votes
by
Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource.

Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can make the count erratic.

No synchronization:

package anonymous;

public class Counting {

        private int increase_counter;

        public int increase() {

                increase_counter = increase_counter + 1;

                return increase_counter;

        }

}

If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because expected final value is 12 but actual final value we get will be 11.

Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.

With synchronization:

package anonymous;

public class Counting {

        private int increase_counter;

        public synchronized int increase() {

                increase_counter = increase_counter + 1;

                return increase_counter;

        }

}

Related questions

+1 vote
asked Jun 2, 2020 in JAVA by Indian
0 votes
asked Jan 24, 2020 in JAVA by rahuljain1
...