views:

282

answers:

3

I am asking this purely to determine the worthwhile-ness of implementing the class in Question ...

Do you know of a Java utility class that takes an un-synchronized instance, uses reflection to investigate that instance, and returns the input instance "wrapped" within synchronized calls ?

( ie: A factory which creates a synchronized delegate class for any instance )

+7  A: 

No, I don't know of anything which does that - and I'd rarely want to use it.

Synchronizing individual operations is rarely a useful feature. Typically you want to synchronize a few operations at a time. Something which simply synchronizes individual operations gives an illusion of thread-safety (enough to make some programmers careless) without dealing with the real decisions of which operations need to be performed in an atomic fashion for any particular situation.

Jon Skeet
+6  A: 

I like Jon Skeet's answer; it's seeing the forest instead of the trees. But to answer the question:

Assuming that the instance belongs to some interface, it's easy to use java.lang.reflect.Proxy to do this.

public final class SynchronizedFactory {
    private SynchronizedFactory() {}

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

    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);
            }
        }
    }
}

This code is not tested, by the way. Use at your own risk.

Chris Jester-Young
A: 

The overhead from reflection would also reduce the speedup that you'd get by threading your code...

Sean Turner