静态方法的参数同步 [英] Synchronization on arguments of static methods

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

问题描述

我有一个关于使用静态方法进行Java同步的问题.

更确切地说,我有一个带有静态方法的类,可以由多个线程同时使用.我班的主要静态方法有一个参数,并在另一个辅助静态方法中将另一个辅助静态方法传递给该参数.

我的问题如下:由于该类一次可以被多个线程使用,所以不存在另一个线程将参数替换为另一个线程的风险吗?

我曾考虑过在我的主要函数的参数变量上使用一个同步块,该变量包含方法的整个代码(因此也调用了辅助函数),但是我不确定这是一个好的解决方案./p>

有人可以帮我吗?

解决方案

我的问题如下:由于该类一次可以被多个线程使用,所以不存在另一个线程将参数替换为另一个线程的风险吗?

不,没有.您会混淆static和堆栈存储.

 static int x;

 static void someMethod(int y1, SomeObject y2) {
     int z;
     ...
 }

在有线程的情况下,所有线程都访问相同的字段x.您需要担心该字段的同步.但是,即使someMethod(...)static方法,y1参数和z方法字段对于调用线程也是本地的.由于其他内存在该线程的调用堆栈中,因此其他线程无法访问该内存.

由于参数y2是对象,因此是一个例外. Java是按值传递的,而基元是通过堆栈传递的.但是,当您按值传递对象时,会传递其引用,因此两个线程可能会传递相同的对象引用,因此您需要担心在那里进行同步.

顺便说一句,虽然肯定允许,但在线程之间调用静态方法并不是最好的模式.实例是可行的方法.它们可以共享静态常量字段等,但是从其他static方法调用各种static方法听起来过于混乱.

I have a question concerning the java synchronization with static methods.

More precisely, I have a class with static methods that can be used concurrently by several threads. The principal static method of my class has one argument and calls the other auxiliary static methods one after the other passing them this argument.

My question is the following: since the class can be used by multiple threads at a time, isn't there a risk that another thread replaces the argument by another one?

I had thought of using a synchronization block on the argument variable of my principal function encompassing the whole code of the method (and thus the calls to auxiliary functions too), but I'm not sure it is a good solution.

Could anyone help me?

解决方案

My question is the following: since the class can be used by multiple threads at a time, isn't there a risk that another thread replaces the argument by another one?

No there isn't. You are confusing static and stack storage.

 static int x;

 static void someMethod(int y1, SomeObject y2) {
     int z;
     ...
 }

In a threaded situation, all threads access the same field x. You need to worry about synchronization of that field. However, even though someMethod(...) is a static method, the y1 argument and the z method field are local to the calling threads. Other threads can't access that memory since its on the thread's call stack.

The exception to this is the argument y2 since it is an object. Java is pass by value and primitives are passed on the stack. However when you pass an object by value, you pass its reference so two threads could get passed the same object reference and you would need to worry about synchronization there.

As an aside, calling static methods between threads although certainly allowed is not the best pattern. Instances are the way to go if possible. They can share static constant fields and the like but calling various static methods from other static methods sounds overly confusing.

这篇关于静态方法的参数同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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