Tuesday, September 29, 2015

How to handle Facebook Likes in thread safe way in Java(Multithreading + synchronized)

12:50 AM By

Multi threading is a concept where multiple operation can be done at the same time. For example, facebook likes. Single photo or Facebook pages can be liked by many Facebook users at that same time.
Today I am going to demonstrate how to handle it in thread safe way and how it will create problem if it is not thread safe.

1. create package with name: mthread
2. Create FacebookPage called FacebookLike as shown in below.

SourceCode: FacebookLike.java

3. Create Java file called SynchronizeFbLike as shown in screenshot:

Source: SynchronizeFbLike.java

We have created Object of FacebookLike page first. final keyword is added as we can only use either final or static object/variable inside Thread.
We have created four different anonymous threads. They have override run methods and inside run we have callled plusone() method of facebook page. Same thing is done in all the threads.
Initial value of likes in now 500(set from construtor).
This program is completely thread safe as we have used synchronized keyword in plusone() method.

So this is the output:

You can see result is working as expected. Now lets see how multi user program can create problem if it is not thread safe.

> remove synchronized keyword from FacebookPage>Plusone() method.
Output is like this:

Now you can see result is totally wrong. If four user hit plusone() result should be 501,502,503,504. Now one thread have replace value incremented by another thread. If we add synchronized keyword. Java add lock in plusone() method so that one thread can only call plusone() method at once.

Hope you have understand basic about how multi threading happen in real world example scenario.
If you enjoy this article feel free to like, share and comment.


Post a Comment