线程安全方法

发布于 2025-01-06 14:48:38 字数 419 浏览 2 评论 0原文

我目前有一个实现单例设计模式的程序:

public class Singleton {
    private static Singleton s;

    private Singleton(){

    }

    public static Singleton getInstance(){
        if(s == null){
            s = new Singleton();
        } 

        return s;
    }
}

在一次采访中有人问我,给定这样的程序,有哪些好的选择可以使 getInstance 方法线程安全。我知道一种方法就是在方法之前标记synchronized,但是面试官说还有其他更有效的方法来处理使方法线程安全的问题。

任何人都可以提供任何想法吗?

I currently have a program implementing a Singleton design pattern:

public class Singleton {
    private static Singleton s;

    private Singleton(){

    }

    public static Singleton getInstance(){
        if(s == null){
            s = new Singleton();
        } 

        return s;
    }
}

I was asked in an interview that given a program like this, what are some good options to make the getInstance method thread safe. I know that one method is just to tag synchronized before the method, but the interviewer said there were other more efficient ways to deal with making methods thread safe.

Can anyone offer any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千秋岁 2025-01-13 14:48:38

我至少能想到三个,尽管其中两个可以归结为相同的原理。

基本上,您可以让类加载器担心线程安全,或者从 Java5 开始使用双重检查锁定。

第一个版本意味着拥有一个包含实际代码的内部类/枚举,第二个版本意味着您使 Singleton 实例可变并使用通常的 if-synchronize-if 解决方案。

At least three I can think of, although two of those boil down to the same principle.

Basically you can either let the classloader worry about thread-safety or use double-checked locking from Java5 onwards.

The first versions means having an inner class/enum that contains the actual code, the second that you make the Singleton instance volatile and use the usual if-synchronize-if solution.

给不了的爱 2025-01-13 14:48:38

哦,我的话,不会再这样了。

编写此代码的最佳方法是最简单的:

public class Singleton {
    private static Singleton s = new Singleton();
    // ...
}

使 getter 同步是第二好的方法。有一些更复杂的方法可以做到这一点,但它们都不值得付出努力 - synchronized 非常便宜,并且不要让任何人告诉您其他情况。

Oh my word, not this again.

The very best way to write this is the simplest:

public class Singleton {
    private static Singleton s = new Singleton();
    // ...
}

Making the getter synchronized is the second best. There are a few more complex ways to do it, but none of them are worth the effort -- synchronized is very cheap, and don't let anyone tell you otherwise.

淑女气质 2025-01-13 14:48:38

1.在类加载时创建实例变量。

优点:

  • 线程安全,无需同步
  • 易于实现

缺点:

  • 过早创建资源可能不会在应用程序中使用。
  • 客户端应用程序无法传递任何参数,因此我们无法重用它。例如,具有用于数据库连接的通用单例类,其中客户端应用程序提供数据库服务器属性。

2.同步getInstance()方法

优点:

  • 保证线程安全。
  • 客户端应用程序可以传递参数
  • 实现延迟初始化

缺点:

  • 由于锁定开销而导致性能降低。
  • 一旦实例变量初始化就不再需要不必要的同步。

3.在if循环和易失性变量中使用synchronized块

优点:

  • 保证线程安全
  • 客户端应用程序可以传递参数
  • 实现延迟初始化
  • 同步开销最小,仅适用于前几个当变量为空时线程。

缺点:

  • 额外的 if 条件

1.Create the instance variable at the time of class loading.

Pros:

  • Thread safety without synchronization
  • Easy to implement

Cons:

  • Early creation of a resource that might not be used in the application.
  • The client application can’t pass any argument, so we can’t reuse it. For example, having a generic singleton class for database connection where client application supplies database server properties.

2.Synchronize the getInstance() method

Pros:

  • Thread safety is guaranteed.
  • Client application can pass parameters
  • Lazy initialization achieved

Cons:

  • Slow performance because of locking overhead.
  • Unnecessary synchronization that is not required once the instance variable is initialized.

3.Use synchronized block inside the if loop and volatile variable

Pros:

  • Thread safety is guaranteed
  • Client application can pass arguments
  • Lazy initialization achieved
  • Synchronization overhead is minimal and applicable only for first few threads when the variable is null.

Cons:

  • Extra if condition
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文