Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Understanding execution of static methods [closed]

There are two methods printA inside class A and printB inside class B. printA is a static method and printB is a non-static method. Both the methods are synchronized. There exact 100 million threads fired on both printA and printB each.

Which method execution will take less time?

My understanding of staticmethods revolves around object creation related stuff. You know, If the class obj is not needed to call static method. Or util methods can be static methods. Or static methods are global and hard to unit test.
In this case I guess that execution of static method will be faster because it will be created once and then reused by every other thread.

like image 410
Himanshu Yadav Avatar asked Sep 18 '26 11:09

Himanshu Yadav


1 Answers

You may find printB faster if you have a lot of objects and multiple processor cores. printA is synchronized on the class object, so all calls to it are done one-at-a-time. printB is synchronized on its object, and so multiple printB calls can run in parallel.

You really need to benchmark your methods, in the context of your program, on a hardware configuration typical of where the program will run.

like image 182
Patricia Shanahan Avatar answered Sep 21 '26 02:09

Patricia Shanahan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!