简体   繁体   中英

Static Synchronized Method to Access Static Field

Hi I have a Utilities class. It is a helper class with all static helper methods. There is a static field within this class.

This class will never be instantiated. It is only used as a helper via the static methods.

Even though this class will never be instantiated, I still think for thread safety sake, the static method should be synchronized while accessing the static field. Am I correct?

public class Utils
{
    private static Map<String, String> messagesMap; 

    public static synchronized String getMessage(String key)
    {
        if(messageMap == null) {
            messageMap = new HashMap<String, String>();
            messageMap.put("john", "hello");
            messageMap.put("mary", "hi");
            // actual population of this map comes from a property file.
        }
        return messageMap(key);
    }
}

I really suggest you initialize the static field at declaration (and mark it final if it's constant) and remove the synchronization from your method. Something like

private static final String message = "Hello"; // <-- needs a semi-colon.
public static String getMessage() {
    return message;
}

Remember, Java String is immutable.

For a Map I would suggest you use a static initialization block (and remove the synchronization and name your variables consistently). Like,

private static Map<String, String> messageMap = new HashMap<>();
static {
    messageMap = new HashMap<String, String>();
    messageMap.put("john", "hello");
    messageMap.put("mary", "hi");
    // actual population of this map comes from a property file.
}

public static String getMessage(String key) {
    return messageMap.get(key);
}

If you want to allow access to and modifications of the static shared state from the multiple threads, the yes, you should use syncronization of some sort. Using synchronized keyword is one way of doing it.

Add a private constructor to your class if you really do want that it shouldn't be instantiated.

Now, If the data fields are only for reference purpose and would never be changed then you just mark them final and the String will do the rest as it is Immutable

Otherwise, you do need to synchronize the methods or code blocks, just make sure that synchronization should be done both at the time of access and modification and using the same lock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM