Java:同步实用程序 [英] Java: Synchronization Utility

查看:152
本文介绍了Java:同步实用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我纯粹是在问这个问题,以确定实施Question中的类的价值...

您知道Java实用程序类采用非同步实例,使用反射来调查该实例,并在同步调用内返回包装"的输入实例吗?

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 )

推荐答案

我喜欢Jon Skeet的回答;它看到的是森林而不是树木.但是要回答这个问题:

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

假设实例属于某个接口,使用java.lang.reflect.Proxy可以很容易地做到这一点.

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

顺便说一下,此代码未经测试.使用风险自负.

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

这篇关于Java:同步实用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆