【问题标题】:Synchronize code inside a servlet filter在 servlet 过滤器中同步代码
【发布时间】:2013-04-04 11:26:30
【问题描述】:

我有一个 servlet 过滤器,在其中我需要使一些代码成为线程安全的。

我给出抽象代码:

doFilter() {
{
......
if (condition1) {
TestClass testObj = StaticTestClass.getTestObj();
testObj = testObj.setTestStr(testObj.getTestStr() + "Success");
StaticTestClass.setTestObj(testObj);
}
.....
}

我想让它线程安全。条件 1 很少为真,因此由于同步而对性能的影响可以忽略不计。所以我可以做以下任何事情:

doFilter() {
{
......
if (condition1) {
TestClass testObj = StaticTestClass.getTestObj();
synchronized(this) {
testObj = testObj.setTestStr(testObj.getTestStr() + "Success");
StaticTestClass.setTestObj(testObj);
}}
......
}

doFilter() {
{
......
if (condition1) {
TestClass testObj = StaticTestClass.getTestObj();
synchronized(testObj) {
testObj = testObj.setTestStr(testObj.getTestStr() + "Success");
StaticTestClass.setTestObj(testObj);
}}
......
}

根据我的理解,从概念上讲,第二个更准确,因为它锁定了 testObj。但是第一个也是正确的,因为容器中只有一个 servlet 过滤器实例。

如果有人有不同意见,请告诉我。

【问题讨论】:

  • condition1 发生了什么变化?
  • condition1 是来自this 的属性吗?
  • 不,condition1 不是来自这个。 StaticTestClass.getTestObj() 正在改变。
  • StaticTestClass.getTestObj 正在改变 condition1?
  • 不,condition1 独立于 StaticTestClass.getTestObj()

标签: java multithreading servlets servlet-filters synchronized


【解决方案1】:

您的理解是正确的:第二个选项是两者中更正确的一个,因为同步语句的目标是访问testObj,而不是this

如果将来您需要在应用中实现新功能并向testObj 添加其他访问权限,则必须在testObj 上进行同步,并且 this。所以你不妨从一开始就这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2012-02-17
    相关资源
    最近更新 更多