微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

下面的类是否实现了正确的Java Singleton Object并提供了线程安全性

如何解决下面的类是否实现了正确的Java Singleton Object并提供了线程安全性

package samples.study;

/**
 * 
 * @author
 */
public class Singleton {
    private Singleton(){}
    private static final Singleton instance = new Singleton();

    public static Singleton getInstance() {
        System.out.println(Thread.currentThread().getName() + " getInstance");
        return Singleton.instance;
    }
}

单元测试用例似乎可以正常工作,并且从多个线程返回了单例对象。帮助我在这里发现任何问题吗?

package samples.study;

import static org.junit.jupiter.api.Assertions.assertSame;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class SingletonTest {

    @BeforeEach
    void setUp() throws Exception {
    }

    @Test
    void test() throws InterruptedException {

        ExecutorService s = Executors.newCachedThreadPool();
        Singleton obj = Singleton.getInstance();
        int threadCount = 10;
        List<Singleton> objList = new ArrayList<Singleton>();
        while (threadCount > 0) {
            s.submit(() -> {
                objList.add(getInstance(s));
            });
            threadCount--;
        }
        while (threadCount > 0) {
            assertSame(obj,objList.get(threadCount));
        }
    }

    public Singleton getInstance(ExecutorService s) {
        Singleton obj = Singleton.getInstance();
        System.out.println("1 = " + Thread.currentThread().getName() + obj);
        return obj;
    }

}

UT的结果:

  • 主要getInstance pool-1-thread-3 getInstance pool-1-thread-2 getInstance 1 =池1线程2samples.study.Singleton@75cbce36 pool-1-thread-4 getInstance 1 = pool-1-thread-4samples.study.Singleton@75cbce36 pool-1-thread-8 getInstance 1 = pool-1-thread-8samples.study.Singleton@75cbce36 pool-1-thread-7 getInstance pool-1-thread-9 getInstance pool-1-thread-6 getInstance pool-1-thread-10 getInstance 1 = pool-1-thread-10samples.study.Singleton@75cbce36 1 = pool-1-thread-6samples.study.Singleton@75cbce36 pool-1-thread-5 getInstance 1 = pool-1-thread-5samples.study.Singleton@75cbce36 1 = pool-1-thread-9samples.study.Singleton@75cbce36 1 = pool-1-thread-7samples.study.Singleton@75cbce36 pool-1-thread-1 getInstance 1 = pool-1-thread-1samples.study.Singleton@75cbce36 1 = pool-1-thread-3samples.study.Singleton@75cbce36

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。