预览版的编译和运行
预览版的编译和运行需要添加额外的参数:
javac --enable-preview -source 21 Test.java
java --enable-preview Test
字符串模板STR(预览版)
介绍
字符串模板STR可以让开发者更简洁的进行字符串拼接(例如拼接sql,xml,json等)。
简单使用
String sport = "basketball";
String msg = STR."i like \{sport}";
System.out.println(msg);//i like basketball
底层原理
STR本身是java.lang.StringTemplate的一个接口。
在StringTemplate中是通过调用interpolate方法来执行的,该方法分别传入了两个参数:
- fragements:包含字符串模板中所有的字面量,是一个List
- values:包含字符串模板中所有的变量,是一个List
而该方法又调用了JavaTemplateAccess中的interpolate方法,经过分析可以得知,它最终是通过String中的join方法将字面量和变量进行的拼接。
所以,STR的最核心原理是String的join方法。
支持方法
拼接多行数据(最重要)
String name = "jordan";
String phone = "13388888888";
String address = "北京";
String json = STR."""
{
"name": "\{name}",
"phone": "\{phone}",
"address": "\{address}"
}
""";
System.out.println(json);
三元运算
int x = 10, y = 20;
String result = STR."\{x} + \{y} = \{x + y}";
System.out.println(result);//10 + 20 = 30
简单调用函数
String result = STR."获取一个随机数: \{Math.random()}";
System.out.println(result);
获取数组数据
String[] cars = {"bmw","benz","audi"};
String result = STR."\{cars[0]},\{cars[1]},\{cars[2]}";
System.out.println(result);
scoped values
介绍
scoped values 是一个隐藏的方法参数,只有方法可以访问scoped values,它可以让两个方法之间传递参数时无需声明形参
1.0阶段 初始阶段:
在UserDao类中编写了saveUser方法,LogDao类中编写了saveLog方法,那么在保存用户的时候需要保证事务,此时就需要在service层获取Connection对象,然后将该对象分别传入到两个Dao的方法中,但对于saveUser方法来说并不是直接使用Connection对象,却又不得不在方法的形参中写上该对象,其实仅从业务上来看,该方法中只要传入User对象就可以了。
2.0阶段 threadlocal:
对于上面的问题,开发者通常会使用ThreadLocal解决,但由于ThreadLocal在设计上的瑕疵,导致下面问题:
- 内存泄漏,在用完ThreadLocal之后若没有调用remove,这样就会出现内存泄漏。
- 增加开销,在具有继承关系的线程中,子线程需要为父线程中ThreadLocal里面的数据分配内存。
- 混乱的可变,任何可以调用ThreadLocal中get方法的代码都可以随时调用set方法,这样就不易辨别哪些方法是按照什么顺序来更新的共享数据。
3.0阶段 虚拟线程:
虚拟线程的出现,解决了内存泄露的问题,但是使得内存承受更大的压力。
4.0阶段 ScopeValue:
ScopeValue类的对象声明为static final ,每个线程都能访问自己的scope value,与ThreadLocal不同的是,它只会被write 1次且仅在线程绑定的期间内有效。
简单上手
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test{
private static final ScopedValue<String> GIFT = ScopedValue.newInstance();
public static void main(String[] args) {
Test t = new Test();
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
pool.submit(()->{
t.giveGift();
});
}
pool.shutdown();
}
//向ScopedValue中添加当前线程的名字
public void giveGift() {
ScopedValue.where(GIFT, Thread.currentThread().getName()).run(() -> receiveGift());
}
public void receiveGift() {
System.out.println(GIFT.get());
}
}
public class Test{
private static final ScopedValue<String> GIFT = ScopedValue.newInstance();
public static void main(String[] args) {
Test t = new Test();
t.giveGift();
}
public void giveGift() {
ScopedValue.where(GIFT, "500元购物卡").run(() -> receiveMiddleMan());
}
//中间人
public void receiveMiddleMan(){
System.out.println(GIFT.get());//500
//修改GIFT中的值,仅对run中调用的receiveGift方法生效
ScopedValue.where(GIFT, "200元购物卡").run(() -> receiveGift());
System.out.println(GIFT.get());//500
}
public void receiveGift() {
System.out.println(GIFT.get()); //200
}
}
switch格式匹配
简单上手
原本的代码:
public class Test{
public static void main(String[] args) {
Integer i = 10;
String str = getObjInstance(i);
System.out.println(str);
}
public static String getObjInstance(Object obj) {
String objInstance = "";
if(obj == null){
objInstance = "空对象"
} else if (obj instanceof Integer i) {
objInstance = "Integer 对象:" + i;
} else if (obj instanceof Double d) {
objInstance = "Double 对象:" + d;
} else if (obj instanceof String s) {
objInstance = "String 对象:" + s;
}
return objInstance;
}
}
switch的写法:
public class Test{
public static void main(String[] args) {
Integer i = 10;
String str = getObjInstance(i);
System.out.println(str);
}
public static String getObjInstance(Object obj) {
return switch(obj){
case null -> "空对象";
case Integer i -> "Integer 对象:" + i;
case Double d -> "Double对象:" + d;
case String s -> "String对象:" + s;
default -> obj.toString();
};
}
}
同时可以在switch里面使用when:
case String s
when s.equalsIgnoreCase("yes") -> {
System.out.println("确定");
}
Unnamed Classes and Instance Main Methods(无名类和实例main方法)
简介
为了方便初学者快速编写第一段java代码,这里提出了无名类和实例main方法,下面代码可以直接运行编译,相当于是少了类的定义,main方法的修饰符和形参也省略掉了
原先的代码:
class MainDemo
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
无名类和实例main方法:
void main() {
System.out.println("Hello, World!");
}
Structured Concurrency(结构化并发编程)
该特性主要作用是在使用虚拟线程时,可以使任务和子任务的代码编写起来可读性更强,维护性更高,更加可靠。
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.function.Supplier;
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Food f = new Test().handle();
System.out.println(f);
}
Food handle() throws ExecutionException, InterruptedException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Supplier<String> yaoZi = scope.fork(() -> "新鲜大腰子烤好了");// 烤腰子的任务
Supplier<String> drink = scope.fork(() -> "奶茶做好了");// 买饮料的任务
scope.join() // 将2个子任务都加入
.throwIfFailed(); // 失败传播
// 当两个子任务都成功后,最终才能吃上饭
return new Food(yaoZi.get(), drink.get());
}
}
}
record Food(String yaoZi, String drink) {
}