Object level locking vs Class level locking in java

Synchronization is ability to restrict access to shared resource to only one thread. When two or more threads need access to shared resource, there has to be some mechanism such that shared resource will be used by only one thread. The process by which we can achieve it is called Synchronization.

Why do you need Synchronization?

Let’s understand this with the help of example.
Let’s say you want to count number of request you got for a particular URL. If you get two requests at the same time, then count may be inconsistent.

Without Synchronization:

 

For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 also sees count as 20 and increment it to 21. This shows that count became inconsistent.

With Synchronization:

You can achieve Synchronization using two ways.

  • synchronized method
  • synchronized block

You can not use synchronized with  instance or class variables.

synchronized method

You can make whole incrementCount() method synchronized so no two thread can access it parallelly.
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 will now see count as 21 and increment it to 22.

synchronized block

You can make use block to synchronize critical section in  incrementCount() method so no two thread can access block concurrently.
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 will now see count as 21 and increment it to 22.

There are two types of locking in java.

  • Object level locking
  • Class level locking

Object level locking:

Object level locking means you want to synchronize non static method or block so that it can be accessed by only one thread at a time for that instance. It is used if you want to protect non static data.
You can achieve Object level locking by following.

Make method synchronized:

Using synchronized block and lock on this:

Using synchronized block and lock on some other object:

Class level locking:

Class level locking means you want to synchronize static method or block so that it can be accessed by only one thread for whole class. If you have 10 instances of class, only one thread will be able to access only one method or block of any one instance at a time. It is used if you want to protect static data.

This can be achieved by following:

Make static method synchronized:

Using synchronized block and lock on .class:

Using synchronized block and lock on some other static object:

Can two threads execute static and non static methods concurrently?

Yes, Since two threads will acquire lock on different objects, they can be executed concurrently without any issues.

If one method of class is synchronized and other method of same class is not synchronized? Can they be executed concurrently by two threads?

Yes, because one thread will require lock to get into synchronized block but second thread which will execute non synchronized method that won’t require any lock, so it can be executed concurrently.

Is it safe to call a synchronized method from another synchronized method?

Yes, it is safe to call a synchronized method from another synchronized method because when you call synchronized method, you will get lock on this object and when you call another synchronized method of same class, it is safe to execute as it already has lock on this object.
For example:

You are actually doing this.

Here if any thread calls method2 from method1, it will already have lock on this object hence It is safe to execute.


import_contacts

You may also like:

Related Posts

  • Get Thread Id in Java
    30 September

    Get Thread Id in Java

    Table of ContentsGet Thread Id in JavaGet Thread Id of Current Running ThreadGet Thread id of Multiple Threads In this article, we will learn to get thread id of a running thread in Java. An Id is a unique positive number generated at the time of thread creation. This id remains unchanged during the lifetime […]

  • ArrayBlockingQueue in java
    19 September

    ArrayBlockingQueue in java

    Table of ContentsWhat is BlockingQueueArrayBlockingQueueFeaturesConstructorsMethodsUsage ScenariosImplementation CodeSummary In this article, we will understand the Java concurrent queue, BlockingQueue. We will then go deep into it’s one of the implementation, ArrayBlockingQueue. What is BlockingQueue BlockingQueue interface was introduced in Java 5 under concurrent APIs and it represents a thread-safe queue in which elements can be added […]

  • Delay java program by few seconds
    11 December

    Delay Java program for few secs

    Table of ContentsUsing Thread.sleepUsing TimeUnit.XXX.sleep methodUsing ScheduledExecutorService In this post, we will see how to delay java program for few secs. We need to delay a java programs in many situation where we want to wait for some other task to finish. There are multiple ways to delay execution of java program. Using Thread.sleep Sleep […]

  • 29 May

    How to print even and odd numbers using threads in java

    Table of ContentsProblemSolution 1Print even and odd numbers using threads in java Solution 2: Using remainder In this post, we will see how to print even and odd numbers using threads in java. see also: How to print sequence using 3 threads in java Problem You are given two threads. You need to print odd […]

  • wait(),notify() and notifyAll() in java
    22 October

    Why wait(), notify() And notifyAll() methods are in Object Class

    In this post, we will see why wait(), notify() And notifyAll() methods are in Object Class And Not in Thread Class. This is one of the most asked java multithreading interview questions. You might know that wait(), notify() And notifyAll() Methods are in Object class and do you know the reason for the same? Let’s […]

  • Custom BlockingQueue in java
    16 October

    Custom BlockingQueue implementation in java

    In this post, we will see how to create your own custom BlockingQueue. This is one of the most asked java interview questions. You need to implement your own BlockingQueue. This question helps interviewer to get your understanding of multithreading concepts. Here is simple implementation of BlockingQueue. We will use array to store elements in […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.