Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does java enumeration ensure thread safety

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to ensure thread safety of java enumeration". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

How enumerations ensure thread safety

If you want to see the source code, you must first have a class, so what is the enumeration type? Is that enum? The answer is obviously not, enum is just like class, just a keyword, it is not a class, so what class is the enumeration maintained by? let's simply write an enumeration:

Public enum t {SPRING,SUMMER,AUTUMN,WINTER;}

Then we use decompilation to see how this code is implemented. After decompilation (decompilation of Java), the code is as follows:

Public final class T extends Enum {private T (String s, int I) {super (s, I);} public static T [] values () {T at []; int I at1 []; System.arraycopy (at = ENUM$VALUES, 0, at1 = new T [I = at.length], 0, I); return at1;} public static T valueOf (String s) {return (T) Enum.valueOf (demo/T, s);} public static final T SPRING;public static final T SUMMER;public static final T AUTUMN;public static final T WINTER Private static final T ENUM$VALUES []; static {SPRING = new T ("SPRING", 0); SUMMER = new T ("SUMMER", 1); AUTUMN = new T ("AUTUMN", 2); WINTER = new T ("WINTER", 3); ENUM$VALUES = (new T [] {SPRING, SUMMER, AUTUMN, WINTER});}}

Through the decompiled code, we can see, public final class T extends Enum, that this class inherits the Enum class, and the final keyword tells us that this class cannot be inherited. When we use enmu to define an enumerated type, the compiler automatically creates a class of final type that inherits from the Enum class, so enumerated types cannot be inherited, and we see several properties and methods in this class.

We can see:

Public static final T SPRING;public static final T SUMMER;public static final T AUTUMN;public static final T WINTER;private static final T ENUM$VALUES []; static {SPRING = new T ("SPRING", 0); SUMMER = new T ("SUMMER", 1); AUTUMN = new T ("AUTUMN", 2); WINTER = new T ("WINTER", 3); ENUM$VALUES = (new T [] {SPRING, SUMMER, AUTUMN, WINTER});}

Are of static type, because the properties of the static type will be initialized after the class is loaded, as we have introduced in the in-depth analysis of Java's ClassLoader mechanism (source level) and the loading, linking and initialization of the Java class. When a Java class is actually used for the first time, static resources are initialized, Java class loading and initialization are thread-safe. Therefore, it is thread safe to create an enum type.

Why the singleton implemented by enumeration is the best way

Among the seven ways to write the singleton pattern, we see that there are seven ways to implement the singleton, among which Josh Bloch, the author of Effective Java, advocates the use of enumeration. since the great god says this is a good way, we need to know why it is good.

1. Enumeration is simple to write.

The writing method is simple. If you look at the seven ways of writing the singleton mode, you can see the difference.

Public enum EasySingleton {INSTANCE;}

You can access it through EasySingleton.INSTANCE.

two。 Enumeration handles serialization on its own

We know that there is a big problem with all the previous singleton patterns, that is, once the Serializable interface is implemented, it is no longer a singleton, because each call to the readObject () method returns a newly created object, and one solution is to use the readResolve () method to avoid this.

However, * * in order to ensure that enumerated types are unique in JVM for each enumerated type and its defined enumerated variables as stated in the Java specification, Java makes special provisions on the serialization and deserialization of enumerated types.

When serializing, Java simply outputs the name property of the enumerated object to the result, and when deserializing, it looks up the enumerated object by name through the valueOf method of java.lang.Enum.

At the same time, the compiler does not allow any customization of this serialization mechanism, so the writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods are disabled. Let's look at this valueOf method:

Public static T valueOf (Class enumType,String name) {T result = enumType.enumConstantDirectory () .get (name); if (result! = null) return result; if (name = = null) throw new NullPointerException ("Name is null"); throw new IllegalArgumentException ("No enum const" + enumType + "." + name);}

As you can see from the code, the code attempts to get an enumerated object named name from the map returned by calling the enumConstantDirectory () method of the Class object enumType, and throws an exception if it does not exist.

If you follow the enumConstantDirectory () method further, you will find that the values () static method of the type enumType is finally called in a reflective manner, which is the method that the compiler created for us above, and then populates the enumConstantDirectory property in the Class object enumType with the return result.

Therefore, JVM has a guarantee for serialization.

3. Enumerated instance creation is thread-safe (thread-safe)

When a Java class is actually used for the first time, static resources are initialized, Java class loading and initialization are thread-safe. Therefore, it is thread safe to create an enum type.

This is the end of the content of "how java enumeration ensures thread safety". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report