Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between static class and normal class

Tags:

java

I am new to Java, and was reading synchronized blocks stuff. I got confused in one of the statement, that during the static class the synchronization uses class instance and normal class uses current object for locking.

Now when both the classes are same, the only difference is that one class is static and other one is normal. Does this make any changes to the interpretation.

Then again my next question will be that in how many ways we can achieve synchronization.

Thanks

like image 652
user1001832 Avatar asked Sep 30 '26 08:09

user1001832


2 Answers

It's not about classes — it's about methods.

synchronized methods are synchronized on the instance; static ones have no instance, so the synchronization is performed on the corresponding Class instance.

like image 182
alf Avatar answered Oct 01 '26 21:10

alf


You confuse the notions of Class, static, instance and how the synchronized block works.

A class is like a blueprint and an instance of that class is like a house build from the blueprint. You can have many houses that are built from the same blueprint just as you can have many instances of a class. A class can have instance methods (non-static, normal if you wish) and static methods. Just like a house (the implementation of a blueprint) can have a light switch function (method) which only makes sence when an actual house exist, in the same way non-static (instance) methods are usable only when you make an instance of a class. On the other hand, imagine that the house blueprints has a button which, upon pressing will calculate the area of the house. That's a function that can work directly on the blueprint but can just as well be used on a house, just like static methods can be used with a (non-instanciated) class but make sense to use in an instance of the class as well.

Synchronized methods when used aquire a lock on the thing that uses them. If you have a static method (either in a non-instantiated class or from an instance of the class) it will aquire the lock on the class, since the static methods is pertinent to the class (not the instance). if you call a dynamic method (which you can only do from an instance of the class) it will aquire a lock on the instance, not on the class.

like image 31
Shivan Dragon Avatar answered Oct 01 '26 20:10

Shivan Dragon