1
\$\begingroup\$

I would like to get the feedback about this code:

import java.util.HashSet;
import java.util.Queue;
import java.util.Set;

public class Utils {

    private final Set<String> permissionsSet = new HashSet<String>(50);
    private PlatformModuleModelLocator modelLocator = Lookup.getDefault().lookup(PlatformModuleModelLocator.class);

    public Boolean hasUserPermission(String permission) {
        synchronized (permissionsSet) {
            if (permissionsSet.isEmpty() && modelLocator.getUserSession() != null) {
                Queue<String> userPermissions = modelLocator.getUserSession().getUserPermissionsFromDB();
                for (String userPermission : userPermissions) {
                    permissionsSet.add(userPermission);
                }
            }
        }
        return permissionsSet.contains(permission);
    }
}

I've tried to fill Set only after first call in multi-threading environment. Can i do it without synchronized block? Please suggest some variants.

PS: It's not from Utils actually, i've just copied this method from application class. PlatformModuleModelLocator returns user permissions like Queue strings. It can have duplicates and i have to iterate over this queue when i need to check permissions. So i decided optimize this block and put this lines to Set.

But it not so matter I look for effective method for lazy initialization collections. How can i initialize my Set after first call?

\$\endgroup\$
  • \$\begingroup\$ Welcome to code review, I hope you get some good answers. \$\endgroup\$ – pacmaninbw Sep 9 '16 at 17:27
  • \$\begingroup\$ This code can't really work since modelLocator will always be null. And I don't feel this code is in the right place: this is a utility class, as per its name, but it actually loads business info such as user permissions. Could you give more details into your application? How are you using this method? \$\endgroup\$ – Tunaki Sep 9 '16 at 18:51
  • \$\begingroup\$ @Tunaki thanks for your comment. You're absolutely right. I've added more info in PS section. \$\endgroup\$ – Vladislav Kysliy Sep 10 '16 at 8:37
  • \$\begingroup\$ any suggestion guys? \$\endgroup\$ – Vladislav Kysliy Sep 16 '16 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.