当前位置: 首页 > 后端技术 > Java

Java新特性20

时间:2023-04-02 10:04:50 Java

Java语言专题系列Java新特性5Java新特性6Java7新特性Java8新特性Java9新特性10Java新特性11Java新特性12Java新特性13Java新特性14特性Java15的新特性Java16的新特性Java17的新特性Java18的新特性Java19的新特性Java20的新特性Java21的新特性-21OpenJDKRuntimeEnvironment(build20+36-2344)OpenJDK64-BitServerVM(build20+36-2344,混合模式,分享)从版本信息可以看出是build20+36JEP429的特性列表:ScopedValues(孵化器)ScopedValueisabettersolutionforpassingvariableswithinthreads/类似于ThreadLocal的父子线程。ThreadLocal提供了一种不需要在方法参数上传递公共变量的方法。InheritableThreadLocal使子线程能够从父线程复制和继承变量。但是ThreadLocal提供了set方法,变量是可变的。另外,remove方法容易被忽略,导致线程池场景内存泄漏。ScopedValue提供了一种不可变、不可复制的解决方案,即不提供set方法,子线程无需复制即可访问父线程的变量。具体使用如下:classServer{publicfinalstaticSc??opedValueLOGGED_IN_USER=ScopedValue.newInstance();privatevoidserve(Requestrequest){//...用户loggedInUser=authenticateUser(request);ScopedValue.where(LOGGED_IN_USER,loggedInUser).run(()->restAdapter.processRequest(request));//...}}通过ScopedValue.where,可以绑定ScopedValue的值,然后在run方法中使用。方法执行后会自行释放,可以使用垃圾回收器回收JEP432:RecordPatterns(SecondPreview)JDK19的JEP405:RecordPatterns(Preview)以Record的模式匹配作为第一预览,JDK20作为后预览第二次预览对嵌套记录的推断。你可以像这样记录点矩形r){if(rinstanceofRectangle(ColoredPoint(Pointp,Colorc),ColoredPointlr)){System.out.println(c);}}总的来说,有几种类型的模式匹配:Pattern:TypePatternParenthesizedPatternRecordPatternTypePattern:LocalVariableDeclarationParenthesizedPattern:(Pattern)RecordPattern:ReferenceTypeRecordStructurePatternRecordStructurePattern:([RecordComponentPatternList])RecordComponentPatternList:Pattern{,Pattern}用于通用推理记录Boxid{String>1(Tbot)if(boinstanceofBox(vars)){System.out.println("字符串"+s);}}也支持嵌套staticvoidtest3(Box>bo){if(boinstanceofBox>(Box(vars))){System.out.println("String"+s);}}JEP433:JDK14JEP305:PatternMatchingforinstanceof(Preview)isasapreviewinJDK15JEP375:PatternMatchingforinstanceof(SecondPreview)asasecondroundofpreviewinJDK16JEP394:PatternMatchingforinstanceofandJDK17introducesJEP406:PatternMatchingforswitch(Preview)JDK18的JEP420:PatternMatchingforswitch(SecondPreview)是第二轮预览JDK19的JEP427:PatternMatchingforswitch(ThirdPreview)作为第三轮预览JDK20作为第四轮预览自第三轮预览以来的主要变化是:抛出MatchException而不是IncompatibleClassChangeErrorswitchwhenthereisnomatchfortheenumerationtype的语法标签更简单。Switch现在支持记录泛型的推断。以前,switch会为null值抛出异常,这需要特殊处理。staticvoidtestFooBar(Strings){if(s==null){System.out.println("糟糕!");返回;}switch(s){case"Foo","Bar"->System.out.println("Great");默认->System.out.println("确定");}}现在你可以直接switchstaticvoidtestFooBar(Strings){switch(s){casenull->System.out.println("Oops");case"Foo","Bar"->System.out.println("Great");默认->System.out.println("确定");}}case支持时,用于写classShape{}classRectangleextendsShape{}classTriangleextendsShape{intcalculateArea(){...}}staticvoidtestTriangle(Shapes){switch(s){casenull:break;case三角形t:if(t.calculateArea()>100){System.out.println("大三角形");休息;}default:System.out.println("一个形状,可能是一个小三角形");}}现在可以这样写staticvoidtestTriangle(Shapes){switch(s){casenull->{break;}caseTriangletwhent.calculateArea()>100->System.out.println("大三角形");case三角形t->System.out.println("小三角形");默认->System.out.println("非三角形");}}针对record泛型的类型推断:recordMyPair(Sfst,Tsnd){};staticvoidrecordInference(MyPairpair){switch(pair){caseMyPair(varf,vars)->...//推断记录模式MyPair(varf,vars)...}}JEP434:ForeignFunction&MemoryAPI(SecondPreview)ForeignFunction&Memory(FFM)APIcontainstwoincubatingAPIJDK14'sJEP370:Foreign-MemoryAccessAPI(Incubator)引入Foreign-MemoryAccessAPIasJEP383:Foreign-MemoryAccessAPI(SecondIncubator)ofincubatorJDK15asJEP393:Foreign-MemoryAccessAPI(ThirdIncubator)作为第三轮,引入了ForeignLinkerAPI(JEP389)FFMAPIinJDK17'sJEP412:ForeignFunction&MemoryAPI(Incubator)作为孵化器引入JDK18'sJEP419:ForeignFunction&MemoryAPI(SecondIncubator)作为第二轮孵化器JEP424:JDK19的ForeignFunction&MemoryAPI(Preview)使用FFMAPI作为预览APIJDK20作为第二轮预览使用示例javac--release20--enable-preview...和java--enable-preview....//1.在C库路径上查找foreignfunctionLinkerlinker=Linker.nativeLinker();SymbolLookupstdlib=linker.defaultLookup();MethodHandleradixsort=linker.downcallHandle(stdlib.find("radixsort"),...);//2.分配堆内存来存储四个字符串String[]javaStrings={"mouse","cat","dog","car"};//3.使用try-with-resources管理堆外内存的生命周期try(ArenaoffHeap=Arena.openConfined()){//4.分配一个堆外内存区域来存储四个指针MemorySegment指针=offHeap.allocateArray(ValueLayout.ADDRESS,javaStrings.length);//5.将字符串从堆上复制到堆外for(inti=0;ifetchURL(url1));varfuture2=executor.submit(()->fetchURL(url2));response.send(future1.get()+future2.get());}catch(ExecutionException|InterruptedExceptione){response.fail(e);}}StringfetchURL(URLurl)抛出IOException{try(varin=url.openStream()){returnnewString(in.readAllBytes(),StandardCharsets.UTF_8);}}JEP437:StructuredConcurrency(SecondIncubator)inJDK19JEP428:StructuredConcurrency(Incubator)在JDK20中作为第一个孵化器作为第二个孵化器JEP438:VectorAPI(FifthIncubator)JDK16引入JEP338:VectorAPI(Incubator)providesjdk。API(SecondIncubator)JEP417:JDK18的VectorAPI(ThirdIncubator)改进后作为第三轮孵化器JDK19JEP426:VectorAPI(FourthIncubator)作为第四轮孵化器JDK20作为第五轮孵化器详情解读上面列出的另外还有一些API的更新和废弃,主要看JDK20ReleaseNotes,这里举几个例子添加项SupportUnicode15.0更新Unicode数据文件到15.0.0AddGarbageCollectorMXBeanforRemarkandCleanupPauseTimeinG1JDK-8297247移去项Thread.suspend/resumeChangedtoThrowUnsupportedOperationExceptionJDK-8249627Thread.StopChangedtoThrowUnsupportedOperationmproved9ExceptionJDK1ofG1ConcurrentRefinementThreadsJDK-8137022以下参数将在未来版本中移除-XX:-G1UseAdaptiveConcRefinement-XX:G1ConcRefinementGreenZone=buffer-count-XX:G1ConcRefinementYellowZone=buffer-count-XX:G1ConcRefinementRedZoneuff=buffer-count-bXX:G1ConcRefinement-count-XX:G1ConcRefinementServiceIntervalMillis=msec有关已弃用项目的完整列表,请参阅JavaSE20deprecated-listjava.net.URL构造函数已弃用JDK-8294241URL构造函数已弃用,您可以使用URL::of(URI,URLStreamHandler)factorymethodinstead知道问题java.lang.Float.floatToFloat16和java.lang.Float.float16ToFloatMayReturnDifferentNaNResultswhenOptimizedbyJITCompiler(JDK-8302976,JDK-8289551,JDK-8289552)JDK20introducedjava.lang。漂浮。浮动到Float16和java.lang.Float.float16ToFloat方法在JIT编译优化过程中可能会返回不同的Nan结果。您可以使用以下参数禁用JIT优化-XX:+UnlockDiagnosticVMOptions-XX:DisableIntrinsic=_floatToFloat16,_float16ToFloatOtheritemsDisabledTLS_ECDH_*CipherSuites(JDK-8279164)TLS_ECDH_*ciphersuitesaredisableddefaultHTTPResponseInputStreamsWillThrowanIOExceptiononInterrupt(JDK-8294047)HttpClientDefaultKeepAliveTimeis30Seconds(JDK-821.7031andhttp2httpidleconnectiontimeoutperiodischangedfrom1200secondsto30secondsSummaryJava20主要有以下特性JEP429:ScopedValues(孵化器)JEP432:记录模式(第二次预览)JEP433:开关模式匹配(第四次预览)JEP434:外部函数和内存API(第二次预览)JEP436:虚拟线程(第二次预览)JEP437:结构化并发(第二个孵化器)JEP438:VectorAPI(第五个孵化器)docJDK20FeaturesJDK20ReleaseNotesConsolidatedSENotesConsolidatedJDK20Java20Releasedeprecated-listTheArrivalofJava20JDK20G1/Parallel/SerialGCchangesJava20DeliversfeaturesforProjectsAmber,Loom和巴拿马Java20:更快的未来正在逼近JDK20安全增强项目Loom的作用域值:最有趣的Java20新功能

最新推荐
猜你喜欢