开发者

Calling static functions from a thread in java?

开发者 https://www.devze.com 2022-12-14 11:03 出处:网络
Lets say I have a class like this in Java: public class Function { public static int foo(int n) { return n+1;

Lets say I have a class like this in Java:

public class Function {
    public static int foo(int n) {
        return n+1;
    }
}

What happens if I call the foo method like this from a thread?

x = Function.foo(y);

Can I do that with two threads, without them 开发者_StackOverflow中文版waiting for each other? Let's say that foo takes a while, and that it gets called a lot, so that each thread would would likely be trying to use foo at the same time. Can they do that, or do I have to make all the methods in Function instance methods and give each thread it's own Function object?


The code you are calling does not store any state, and thus will return deterministically whether called from one thread or many - and its not like the "lines of code" needs to be guarded (as you seem to imply by your question), because its ok to run the "same lines of code" from multiple threads, provided they dont share data (which in this case, doesnt).

Problem comes if you had code like

public class Function {
    private static int last = 0;
    public static int foo(int n) {
        last += n; 
        return last; 
    }
}

this is when you start to need to worry about different threads clobbering the static last.


As long as foo() uses just parameters and local variables, any number of threads can call it at once (and if you have multiple cores, they might even execute it at the same time).

The problem with calling the same method from multiple threads appears when that method accesses shared state. For example, if Functions also declared a static map:

private static Map<String,Object> myObjects;

In this case, two threads could attempt to update the map at the same time. Since most map implementations aren't internally synchronized, the two threads could change the same internal structures, and corrupt the map data.

Synchronizing on shared state, while easy in theory, is not so easy in practice. For example, you could simply use a ConcurrentHashMap, which can be accessed by multiple threads simultaneously. However, it makes no guarantees about preservation of state between calls, so you could put something into the map at time X, and some other thread could remove it at time Y, before your first thread tries to access it again at time Z.


You should be aware that each thread has its own stack, and n (the only variable here) lives on the stack; so those threads do not interfere.

0

精彩评论

暂无评论...
验证码 换一张
取 消