0

I'm trying to initialize a MethodHandle for a non-public method in an upstream library.

private static Method OF_METHOD;

static Method ofMethod() {
    if (OF_METHOD == null) {
        try {
            OF_METHOD = RequestObject.class.getDeclaredMethod(
                    "of", Class.class, String.class, String.class,
                    Object.class, Object.class);
            if (!OF_METHOD.isAccessible()) {
                OF_METHOD.setAccessible(true);
            }
        } catch (final NoSuchMethodException nsme) {
            throw new RuntimeException(nsme);
        }
    }
    return OF_METHOD;
}

private static MethodHandle OF_HANDLE;

static MethodHandle ofHandle() {
    if (OF_HANDLE == null) {
        try {
            OF_HANDLE = MethodHandles.lookup().unreflect(ofMethod());
        } catch (final ReflectiveOperationException roe) {
            throw new RuntimeException(roe);
        }
    }
    return OF_HANDLE;
}

And my SpotBugs Bug Detecter Report says the ofMethod() has a LI_LAZY_INIT_UPDATE_STATIC problem.

I understand what it's saying. I see those two steps(assigning and setting accessible) are problematic in multi-threaded environment.

How can I solve the problem? Should I apply Double-checked locking?

Or should I put ofMethod() logic into ofHandle()?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

0

I'm answering for my own question.

The idea of holding a lazy object reference is a bad idea.

Even with the Double-checked locking,

private static volatile Method OF_METHOD;

static Method ofMethod() {
    Method ofMethod = OF_METHOD;
    if (ofMethod == null) {
        synchronized (JacksonRequest.class) {
            ofMethod = OF_METHOD;
            if (ofMethod == null) {
                try {
                    ofMethod = ...;
                } catch (final NoSuchMethodException nsme) {
                    throw new RuntimeException(nsme);
                }
                if (!ofMethod.isAccessible()) {
                    ofMethod.setAccessible(true);
                }
                OF_METHOD = ofMethod;
            }
        }
    }
    return ofMethod;
}

Anyone can change the accessible state.

I ended up with following code which doesn't depend on any external variables.

static Method ofMethod() {
    try {
        final Method ofMethod = ...;
        if (!ofMethod.isAccessible()) {
            ofMethod.setAccessible(true);
        }
        return ofMethod;
    } catch (final NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    }
}
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184