分享

java – 如何向线程池的旧线程提供当前的vaadin会话?

 印度阿三17 2019-06-28

我在理解VaadinSession.getCurrent()的引用后面临一个问题

Gets the currently used session. The current session is automatically
defined when processing requests to the server and in threads started
at a point when the current session is defined (see
InheritableThreadLocal). In other cases, (e.g. from background threads
started in some other way), the current session is not automatically
defined.

具体以下几点对我来说很难理解,

… in threads started
at a point when the current session is defined (see
InheritableThreadLocal).

那是什么意思 ?

我的理解是,如果在定义新会话之前创建线程,或者在旧会话中创建线程,则它将不会引用当前新创建的会话.

目前我有线程池,一些线程指的是现在关闭的旧会话然后我将面临在这些线程中使用会话的问题.

我正在使用带vaadin的spring,特别是@Async方法调用.

@Async
public static methodX() {
    //I have used session inside it
}

问题是,thread1已被用于执行methodX,现在我已经使用了session session1,在用户注销后,这个session1将被关闭.

现在,当新用户登录到具有session2的系统并再次使用thread1执行此方法时,此方法仍然使用session1而不是session2,并且当方法尝试从关闭的session1获取数据时会产生问题.

我的问题:

>为什么Vaadin无法提供或通知旧线程(即属于旧(已关闭)会话的线程)有关新定义的会话?
>为这些线程提供会话的最佳方法是什么?

解决方法:

这意味着如果您在单独的线程中处理数据,则不会有当前会话:

所以这段代码:

Runtime runtime = Runtime.getRuntime();                 
final Process process = runtime.exec(action);
new Thread() {
    public void run() {
        try {
            System.out.println(VaadinSession.getCurrent());
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}.start();

在您的vaadin项目中将打印一个旧会话,即Thread启动时的会话.

编辑

我认为Vaadin无法为旧线程提供新会话以避免数据损坏问题.我的意思是如果5个Threads正在编辑同一个会话,你将遇到问题……

您的解决方案是为池中的每个线程提供Session,但我真的不知道如何实现这一点,Google到目前为止还没有给我答案.

编辑:另一种可能的解决方

使用HashMap< int,VaadinSession>创建一个类来存储每个Sessions(使用SessionListener).以静态的方式.

创建线程时,请为其提供需要使用的会话的ID(id是与HashMap中所需会话对应的键).然后每次编辑,销毁会话时,只需在HashMap中编辑它.

由于此HashMap的静态行为,您可以随时从任何线程访问它,您唯一需要的是与线程中的会话相对应的int id.

来源:https://www./content-1-276551.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多