1

The following Utility class calls within itself the same static methods, but has no shared global variables. But it looks like the method nameTo() is "shared" and an issue. Am I right with it, and that it's unsafe?

public class Utility 
{
    public static MyObject create_1(boolean b)
    {
        MyObject o = new MyObject();
        o.setName(nameTo(b));           
        return o;
    }

    public static MyObject create_2(boolean b)
    {
        MyObject o = new MyObject();
        o.setName(nameTo(b));           
        return o;
    }

    public static String nameTo(boolean b)
    {
        if(b)
            return "NameA";
        else
            return "NameB";         
    }
}
4

3 回答 3

3

由于您的nameTo()方法是无状态的,因此在多线程上下文中没有问题。代码可以在线程之间尽可能多地共享。重要的是数据。

于 2013-08-26T10:32:13.887 回答
2

所有静态方法在线程之间共享。并且由于该nameTo()方法没有任何正在使用的共享状态,因此它是线程安全的。

class Utility{

  private static int sharedValue; //something like counter of how many times nameTo() is called

  public static String nameTo(boolean b){
     //logic

     sharedValue++; //this will not be thread safe as it is shared state and being updated  in parallel

  }
}
于 2013-08-26T10:32:14.010 回答
1

您没有 a 中的数据global state,因此我看不到任何线程安全问题。这些方法都没有改变任何shared data.

于 2013-08-26T10:33:39.673 回答