Javatpoint Logo
Javatpoint Logo

Static Synchronization

If you make any static method as synchronized, the lock will be on the class not on object.

static synchronization

Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this problem.

Example of static synchronization

In this example we are applying synchronized keyword on the static method to perform static synchronization.

Test it Now
Output: 1
       2
       3
       4
       5
       6
       7
       8
       9
       10
       10       
       20
       30
       40
       50
       60
       70
       80
       90
       100
       100
       200
       300
       400
       500
       600
       700
       800
       900
       1000
       1000
       2000
       3000
       4000
       5000
       6000
       7000
       8000
       9000
       10000
       

Same example of static synchronization by annonymous class

In this example, we are using annonymous class to create the threads.

Test it Now
Output: 1
       2
       3
       4
       5
       6
       7
       8
       9
       10
       10       
       20
       30
       40
       50
       60
       70
       80
       90
       100
       100
       200
       300
       400
       500
       600
       700
       800
       900
       1000
       1000
       2000
       3000
       4000
       5000
       6000
       7000
       8000
       9000
       10000
       

Synchronized block on a class lock:

The block synchronizes on the lock of the object denoted by the reference .class name .class. A static synchronized method printTable(int n) in class Table is equivalent to the following declaration:

Next TopicDeadlock In Java




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA