java - 下面的类是否实现了正确的 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的结果:
- main getInstance pool-1-thread-3 getInstance pool-1-thread-2 getInstance 1 = pool-1-thread-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
解决方案
推荐阅读
- canvas - 在树莓派上安装 Canvas
- javascript - 如何使用 Javascript 从此格式 (2020-09-20 12:25:01) 获取时间戳
- azure - 使用 vnet 集成的 azure 应用服务的静态 ip
- react-native - React 本机 java.lang.string 不能强制转换为 java.lang.double
- blazor-webassembly - 我可以将 Blazor Wasm Standalone 与 Microsoft.Identity.Web 一起使用吗
- pandas - MS Access pyodbc Pandas 数据帧 to_sql 抛出无效的精度值
- javascript - 使用 JS 或 jQuery 在移动设备上更改(添加/删除)CSS 类
- python - 即使设置为写入模式,也没有这样的文件或目录。如何解决这个问题,我该如何正确地做到这一点?
- excel - Excel - 在一列中查找重复项,然后将数量汇总到另一列?
- mysql - 如何从 MySQL 函数中引用当前列值