java使用类的静态变量,在Java中,是否需要同步不使用静态或类变量的方法?

Do methods that only use local variables inside suffer any threading issues ?. Somewhere it was mentioned that the method with local variables are copied to each thread stack frame to work with and do not need to synchronized for multithreaded implementation unless it uses class level or static references/variables ?

解决方案

If your method only operates on parameters and locally-defined (as opposed to class member) variables then there are zero synchronization problems to worry about.

But...

This means any mutable reference types you use must live and die only within the scope of your method. (Immutable reference types aren't a problem here.) For example this is no problem:

int doSomething(int myParameter)

{

MyObject working_set = new MyObject();

interim = working_set.doSomethingElse(myParameter);

return working_set.doSomethingElseAgain(interim);

}

A MyObject instance is created within your method, does all of its work in your method and is coughing up blood, waiting to be culled by the GC when you exit your method.

This, on the other hand, can be a problem:

int doSomething(int myParameter)

{

MyObject working_set = new MyObject();

interim = working_set.doSomethingElse(myParameter);

another_interim = doSomethingSneaky(working_set);

return working_set.doSomethingElseAgain(another_interim);

}

Unless you know for sure what's going on in doSomethingSneaky(), you may have a need for synchronization somewhere. Specifically you may have to do synchronization on the operations on working_set because doSomethingSneaky() could possibly store the reference to your local working_set object and pass that off to another thread while you're still doing stuff in your method or in the working_set's methods. Here you'll have to be more defensive.

If, of course, you're only working with primitive types, even calling out to other methods, passing those values along, won't be a problem.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值