Java: Sync Utility

I ask about this solely to determine the feasibility of implementing the class in question ...

Do you know about the Java utility class that accepts an unsynchronized instance, uses reflection to examine that instance, and returns an input instance wrapped in synchronized calls?

(i.e. A factory that creates a synchronized delegate class for any instance)

+3
source share
4 answers

I like John Skeet's answer; he sees a forest instead of trees. But to answer the question:

Assuming the instance belongs to some interface, this is easy to use java.lang.reflect.Proxy.

public final class SynchronizedFactory {
    private SynchronizedFactory() {}

    public static <T> T makeSynchronized(Class<T> ifCls, T object) {
        return ifCls.cast(Proxy.newProxyInstance(
                object.getClass().getClassLoader(),
                new Class<?>[] {ifCls},
                new Handler<T>(object)));
    }

    private static class Handler<T> implements InvocationHandler {
        private final T object;

        Handler(T object) {
            this.object = object;
        }

        @Override
        public Object invoke(Object proxy, Method method,
                Object[] args) throws Throwable {
            synchronized (object) {
                return method.invoke(object, args);
            }
        }
    }
}

, . .

+7

, , , .

. . -, , (, ), , - .

+8

, -. , , . !

/**
 * Utility that can take any object that implements a given interface and returns
 * a proxy that implements the same interface and synchronizes all calls that are
 * delegated to the given object. From Chris Jester-Young, http://about.me/cky
 * @param interfaceClass The interface to synchronize. Use MyInterface.class.
 * @param object The object to synchronize that implements the given interface class.
 * @return A synchronized proxy object that delegates to the given object.
 */
public static <T> T makeSynchronized(Class<T> interfaceClass, final T object) {
    return interfaceClass.cast(
        Proxy.newProxyInstance(
            object.getClass().getClassLoader(),
            new Class<?>[]{interfaceClass},
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    synchronized (object) {
                        return method.invoke(object, args);
                    }
                }
            }
        )
    );
}
+1
source

Reflection overhead will also reduce the speed you get by typing a code ...

-1
source

Source: https://habr.com/ru/post/1706321/


All Articles