【发布时间】:2012-10-26 07:18:04
【问题描述】:
我正在按照 thread local pattern 实现一个 vaadin 应用程序。
应用程序的状态由多个工作线程修改。因此,为了通知应用程序其状态已更改,我添加了一个进度指示器。
阅读进度指示器示例,我看到了:
// All modifications to Vaadin components should be synchronized
// over application instance. For normal requests this is done
// by the servlet. Here we are changing the application state
// via a separate thread.
synchronized (getApplication()) {
prosessed();
}
所以基本上,我想我只需修改对getApplication 的调用即可获取我的应用程序实例(只需调用getCurrent):
private static ThreadLocal<MyApplication> currentApplication = new ThreadLocal<MyApplication>();
@Override
public void init() {
setCurrent(this); // So that we immediately have access to the current application
// initialize mainWindow and other stuff
// Register a transaction listener that updates our ThreadLocal with each request
if (getContext() != null) {
getContext().addTransactionListener(this);
}
}
/**
* @return the current application instance
*/
public static MyApplication getCurrent() {
return currentApplication.get();
}
问题是我的工作线程死于饥饿,因为它无法获取应用程序上的互斥锁。 vaadin 论坛提供的一种解决方案是使用InheritableThreadLocal。它有效,但我不明白为什么。
来自 javadoc:
这个类扩展了 ThreadLocal 以提供值的继承 父线程到子线程:创建子线程时, child 接收所有可继承线程本地的初始值 父级具有值的变量。通常孩子的价值观 将与父母的相同;但是,孩子的价值可以是 通过重写父级的任意函数 此类中的 childValue 方法。
优先使用可继承的线程局部变量 维护每个线程属性时的线程局部变量 在变量(例如,用户 ID、交易 ID)中必须自动 传输到任何创建的子线程。
我的工作线程无法获得锁,因为它没有接收到初始值? 我误解了什么吗? 除了this problem,我应该注意使用 InheritableThreadLocal 的潜在陷阱是什么?
谢谢。
【问题讨论】:
标签: java multithreading concurrency vaadin