How to synchronize static method in java.
Posted
by Summer_More_More_Tea
on Stack Overflow
See other posts from Stack Overflow
or by Summer_More_More_Tea
Published on 2010-06-02T13:19:20Z
Indexed on
2010/06/02
13:23 UTC
Read the original article
Hit count: 221
Hi there:
I come up with this question when implementing singleton pattern in Java. Even though the example listed blow is not my real code, yet very similar to the original one.
public class ConnectionFactory{
private static ConnectionFactory instance;
public static synchronized ConnectionFactory getInstance(){
if( instance == null ){
instance = new ConnectionFactory();
}
return instance;
}
private ConnectionFactory(){
// private constructor implementation
}
}
Because I'm not quite sure about the behavior of a static synchronized method, I get some suggestion from google -- do not have (or as less as possible) multiple static synchronized methods in the same class. I guess when implementing static synchronized method, a lock belongs to Class object is used so that multiple static synchronized methods may degrade performance of the system.
Am I right? or JVM use other mechanism to implement static synchronized method? What's the best practice if I have to implement multiple static synchronized methods in a class?
Thank you all!
Kind regards!
© Stack Overflow or respective owner