Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7992723
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T13:38:59+00:00 2026-06-04T13:38:59+00:00

I’ve implemented a little helper class that provides an easy fail-safe implementation of the

  • 0

I’ve implemented a little helper class that provides an easy fail-safe implementation of the enum’s valueOf method. This means in case the value is not found, it returns null instead of an exception.

Here’s the code:

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import java.io.Serializable;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * This permits to easily implement a failsafe implementation of the enums's valueOf method
 * </p>
 *
 * <p>
 * Basic usage exemple on an enum class called MyEnum:
 * FailSafeValueOf.get(MyEnum.class).valueOf("EnumName");
 * </p>
 *
 * @author Sebastien Lorber <i>(lorber.sebastien@gmail.com)</i>
 */
public class FailSafeValueOf<T extends Enum<T>> implements Serializable {

    /**
     * This will cache a FailSafeValueOf for each enum so that we do not need to recompute a map each time
     */
    private static final Map< Class<? extends Enum<?>> , FailSafeValueOf<? extends Enum<?>> >  CACHE = Maps.newHashMap();


    private final Map<String,T> nameToEnumMap;
    private FailSafeValueOf(Class<T> enumClass) {
        Map<String,T> map = Maps.newHashMap();
        for ( T value : EnumSet.allOf(enumClass)) {
            map.put( value.name() , value);
        }
        this.nameToEnumMap = ImmutableMap.copyOf(map);
    }

    /**
     * Returns the value of the given enum element
     * If the element is not found, null will be returned, and no exception will be thrown
     * @param enumName
     * @return
     */
    public T valueOf(String enumName) {
        return nameToEnumMap.get(enumName);
    }


    /**
     * Get a failsafe value of implementation for a given enum
     * @param enumClass
     * @param <U>
     * @return
     */
    public static <U extends Enum<U>> FailSafeValueOf<U> get(Class<U> enumClass) {
        FailSafeValueOf<U> fsvo = (FailSafeValueOf<U>)CACHE.get(enumClass);
        if ( fsvo == null ) {
            synchronized (FailSafeValueOf.class) {
                fsvo = (FailSafeValueOf<U>)CACHE.get(enumClass);
                if ( fsvo == null ) {
                    fsvo = new FailSafeValueOf<U>(enumClass);
                    CACHE.put(enumClass,fsvo);
                }
            }
        }
        return fsvo;
    }

}

Because i don’t want the (little) overhead of creating a new FailSafeValueOf at each access, i’ve made a cache that keeps for each enum already accessed an already built FailSafeValueOf instance.

I’m not used to handle concurrency. A concurrent access may not be a big problem in such a case as FailSafeValueOf is immutable and 2 different instances of FailSafeValueOf can be returned by the get method for a same enum.
But i’d like to know if my implementation of thread-safety is the way to do, and if it’s really thread-safe? (mostly for learning purpose)

I don’t want to make my method synchronized because after some time, all FailSafeValueOf are created in the cache, and there is no need to forbid concurrent threads to enter the get method.

So what i’ve made is to check first if there’s a cache miss, and then create a synchronized block that will atomically: check again the cache and eventually create the instance.
Is it thread-safe and the way to do for such a need?

By the way, enums often have a small number of values. In such a case, is the HashMap an appropriate structure? Is it faster to iterate over the EnumSet and get the appropriate value, instead of using a cache?


Edit:

Please notice that my class is not so useful because the Guava team has releated a method Enums.getIfPresent() which returns an Optional

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T13:39:00+00:00Added an answer on June 4, 2026 at 1:39 pm

    Your class is not thread-safe because you are not synchronizing around the CACHE.get() method. This assumes that Maps.newHashMap() returns a HashMap and not a ConcurrentHashMap class. You can see this in this code snippet:

        // you need to move your synchronized block out to here
        FailSafeValueOf<U> fsvo = (FailSafeValueOf<U>)CACHE.get(enumClass);
        if ( fsvo == null ) {
            synchronized (FailSafeValueOf.class) {
               ...
               CACHE.put(enumClass,fsvo);
            }
        }
    

    You would need to move the synchronized around the CACHE.get(...) or switch to using a ConcurrentHashMap if that method is called frequently. The problem is that the HashMap would be updated by another thread while the current thread is reading from it — this can easily cause problems because of race conditions.

    Although slightly different, you should also look into the class “Double Check Locking” documentation to understand more the difficulties about trying to save yourself from synchronization like this.

    Lastly, I would synchronize on the CACHE object instead of the class which is not recommended unless you really need to have that lock granularity.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I've got a string that has curly quotes in it. I'd like to replace
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.