public class Main {
public static void main(String[] args) {
RecordB recordB = new RecordB(true);
switch(recordB) {
case RecordB b when b.bool() -> System.out.println("It's true");
case RecordB b when !b.bool() -> System.out.println("It's false");
}
}
record RecordB(boolean bool) { }
}
Run Code Online (Sandbox Code Playgroud)
当编译上面的代码时,编译器会产生以下信息:the switch statement does not cover all possible input values
从我的角度来看,这不一定是真的。所以这是我的问题:任何受保护的模式是否总是使编译器的 switch 表达式不详尽,或者我在这里遗漏了一些东西?
我正在寻找一个问题的答案:方法.toArray(IntFunction generator)如何知道新数组的大小.
实际上我知道如何使用这个方法来创建包含所有stream元素的新数组(例如String[]::new, Size -> new String[Size]),但在原始的java代码中我们可以看到IntFunction<A[]>生成器将给定的函数应用于int参数.我的问题是这个函数如何获取流的元素数量.
我已经阅读了这个课程的源代码3个小时,但我找不到答案.
非常感谢!
我写下了这段代码:
public class Main {
private boolean stopThread = false;
private int counter = 0;
public static void main(String[] args) throws InterruptedException {
final Main main = new Main();
new Thread(() -> {
try {
System.out.println("Start");
Thread.sleep(100);
System.out.println("Done");
main.stopThread = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
while (!main.stopThread) {
main.counter++;
}
System.out.println(main.counter);
}).start();
System.out.println("End");
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,while循环将永远运行。我对此有点挣扎,我对应用于此代码的优化 JIT 类型感到困惑。
首先我认为这是具有知名度的问题stopThread变量,但即使它是一个真正的while循环应该有点晚停比我分配stopThread到true时(从第1线程CPU缓存得到刷新到主存储器),所以事实并非如此。看起来像 JIT 硬编码false …
我在阅读Vavr的Lazy源码时遇到过如下代码:
private transient volatile Supplier<? extends T> supplier;
private T value; // will behave as a volatile in reality, because a supplier volatile read will update all fields (see https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#volatile)
Run Code Online (Sandbox Code Playgroud)
public T get() {
return (supplier == null) ? value : computeValue();
}
private synchronized T computeValue() {
final Supplier<? extends T> s = supplier;
if (s != null) {
value = s.get();
supplier = null;
}
return value;
}
Run Code Online (Sandbox Code Playgroud)
这是一个著名的模式,称为“双重检查锁定”,但对我来说它看起来很糟糕。假设我们将此代码嵌入到多线程环境中。如果该get()方法由第一个线程调用并且供应商构造了一个新对象,(对我而言)由于以下代码的重新排序,另一个线程有可能看到半构造的对象:
private synchronized T computeValue() { …Run Code Online (Sandbox Code Playgroud) java ×4
arrays ×1
concurrency ×1
java-21 ×1
java-8 ×1
java-stream ×1
jit ×1
jvm ×1
lazy-loading ×1
performance ×1
vavr ×1
volatile ×1