Java: Understanding execution of static methods

java, performance

Solution

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.

Problem

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 `static`methods 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.

Original source