"thread safe multitons in java" Code Answer

1

this will provide you a threadsafe storage mechanism for your multitons. the only downside is that it is possible to create a multiton that will not be used in the putifabsent() call. the possibility is small but it does exist. of course on the remote chance it does happen, it still causes no harm.

on the plus side, there is no preallocation or initialization required and no predefined size restrictions.

private static concurrenthashmap<integer, multiton> instances = new concurrenthashmap<integer, multiton>();

public static multiton getinstance(int which) 
{
    multiton result = instances.get(which);

    if (result == null) 
    {
        multiton m = new multiton(...);
        result = instances.putifabsent(which, m);

        if (result == null)
            result = m;
    }

    return result;
}
By Oin on May 13 2022

Answers related to “thread safe multitons in java”

Only authorized users can answer the Search term. Please sign in first, or register a free account.