Static Synchronized Methods

In my previous post, i elaborated object level lock that exist for each instance of a class. We can also use class level lock where all instances of a particular class can share it. As we discussed, any class loaded by java virtual machine has one class level lock. If we make a method static and syncronized, a thread must have to get exclusive class level access before entering the method. A class level lock can be used to control concurrent access to static member variables. Modifying previous example, to generate unique sequence numbers, the code and output is listed below.

Possible output is :
t1 :1001
t2 :1002
t3 :1003
t4 :1004
t5 :1005
t6 :1006
t7 :1007
t8 :1008

In above code, our main idea was to generate a unique series of numbers. I used static synchronized method to ensure that only one thread at a time is allowed to enter into method. The above given technique eliminates the real issue of duplicate number generated.

No Responses