Hello everyone, I'm Alang. I need to use current limiting in my work recently. This article introduces common current limiting methods.
The article is continuously updated, you can follow the official account programmer Alang or visit the unread code blog .
This article has been included in Github.com/niumoo/JavaNotes , welcome to Star.
Java 18 was officially released on March 22, 2022. Java 18 is not a long-term support version. This update brings a total of 9 new features.
OpenJDK Java 18 download: https://jdk.java.net/18/
OpenJDK Java 18 Documentation: https://openjdk.java.net/projects/jdk/18/
JEP | describe |
---|---|
JEP 400 | Default is UTF-8 |
JEP 408 | simple web server |
JEP 413 | Code snippets from the Java API documentation |
JEP 416 | Reimplement core reflection using method handles |
JEP 417 | Vector API (three incubations) |
JEP 418 | Internet Address Resolution SPI |
JEP 419 | Foreign Function & Memory API (second incubation) |
JEP 420 | switch pattern matching (secondary preview) |
JEP 421 | Deprecated complete removal |
JEP 400: Default UTF-8 Character Encoding
JDK has always supported UTF-8 character encoding. This time, UTF-8 is set as the default encoding, that is, without any specification, all JDK APIs that require encoding use UTF-8 encoding by default. In this way, coding problems caused by different systems, different regions, and different environments can be avoided.
Mac OS uses UTF-8 as the default encoding by default, but on other operating systems, the encoding may depend on system configuration or locale settings. For example, windows in mainland China use GBK as the default encoding. When learning Java for the first time, many students may have encountered a situation where a normal Java class is written, but garbled characters appear when running in the command console of the windows system.
Use the following command to output the current encoding of the JDK.
# Mac 系统,默认 UTF-8
➜ ~ java -XshowSettings:properties -version 2>&1 | grep file.encoding
file.encoding = UTF-8
file.encoding.pkg = sun.io
➜ ~
Let's write a simple Java program, output the default character encoding, and then output the Chinese character "Hello" to see the difference between Java 18 and Java 17.
System environment: Windows 11
import java.nio.charset.Charset;
public class Hello{
public static void main(String[] args) {
System.out.println(Charset.defaultCharset());
System.out.println("你好");
}
}
As can be seen from the running results below, the default character encoding output by running JDK 17 is GBK, and the output Chinese "Hello" is garbled; the garbled characters are because the default text editor encoding of VsCode is UTF-8, while the Chinese "Hello" is garbled. The default character encoding of Windows 11 in the region is GBK, which is also the encoding obtained by JDK 17 by default, so it will be garbled in console output; and the default encoding of JDK 18 output is UTF-8, so you can output Chinese "Hello" normally ".
JEP 408: Simple Web Server
In Java 18, a new command is provided jwebserver
, running this command can start a simple, minimal static web server, it does not support CGI and Servlet, so the best usage scenario is to use Testing, education, presentations, etc.
In fact, many platforms such as Python, Ruby, PHP, Erlang, etc. provide out-of-the-box web servers. It can be seen that a simple web server is a common requirement. Java has never supported this aspect, but now it is possible.
In Java 18, use jwebserver
to start a web server, which publishes the current directory by default.
Create a web page file index.html in the current directory
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>标题</h1>
</body>
</html>
start jwebserver
.
➜ bin ./jwebserver
Binding to loopback by default. For all interfaces use "-b 0.0.0.0" or "-b ::".
Serving /Users/darcy/develop/jdk-18.jdk/Contents/Home/bin and subdirectories on 127.0.0.1 port 8000
URL http://127.0.0.1:8000/
Browser access:
When there is a request, the request information will be output in the console:
127.0.0.1 - - [26/3月/2022:16:53:30 +0800] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [26/3月/2022:16:55:13 +0800] "GET / HTTP/1.1" 200 -
Through the help
parameter, you can view the supported parameters of jwebserver
.
➜ bin ./jwebserver --help
Usage: jwebserver [-b bind address] [-p port] [-d directory]
[-o none|info|verbose] [-h to show options]
[-version to show version information]
Options:
-b, --bind-address - 绑定地址. Default: 127.0.0.1 (loopback).
For all interfaces use "-b 0.0.0.0" or "-b ::".
-d, --directory - 指定目录. Default: current directory.
-o, --output - Output format. none|info|verbose. Default: info.
-p, --port - 绑定端口. Default: 8000.
-h, -?, --help - Prints this help message and exits.
-version, --version - Prints version information and exits.
To stop the server, press Ctrl + C.
JEP 413: Support for code snippets in Javadoc
Before Java 18, the introduction of code snippets in Javadoc has been supported, which can better display descriptive information in some scenarios, but the previous support functions are limited. For example, I want to highlight a certain piece of code in the code snippet is powerless. . Now Java 18 optimizes this problem, adding @snippet
to introduce more advanced code snippets.
Before Java 18, use <pre>{@code ...}</pre>
to import code snippets.
/**
* 时间工具类
* Java 18 之前引入代码片段:
* <pre>{@code
* public static String timeStamp() {
* long time = System.currentTimeMillis();
* return String.valueOf(time / 1000);
* }
* }</pre>
*
*/
After generating Javadoc, the effect is as follows:
Highlight code snippets
Since Java 18, you can use @snippet
to generate comments and to highlight a code fragment.
/**
* 在 Java 18 之后可以使用新的方式
* 下面的代码演示如何使用 {@code Optional.isPresent}:
* {@snippet :
* if (v.isPresent()) {
* System.out.println("v: " + v.get());
* }
* }
*
* 高亮显示 println
*
* {@snippet :
* class HelloWorld {
* public static void main(String... args) {
* System.out.println("Hello World!"); // @highlight substring="println"
* }
* }
* }
*
*/
The effect is as follows, more intuitive and better.
Regular highlight code snippet
You can even use regular expressions to highlight certain keywords in a paragraph:
/**
* 正则高亮:
* {@snippet :
* public static void main(String... args) {
* for (var arg : args) { // @highlight region regex = "\barg\b"
* if (!arg.isBlank()) {
* System.out.println(arg);
* }
* } // @end
* }
* }
*/
The generated Javadoc looks like this:
replace code snippet
You can use regular expressions to replace a piece of code.
/**
* 正则替换:
* {@snippet :
* class HelloWorld {
* public static void main(String... args) {
* System.out.println("Hello World!"); // @replace regex='".*"' replacement="..."
* }
* }
* }
*/
This comment produces the following Javadoc effect.
class HelloWorld {
public static void main(String... args) {
System.out.println(...);
}
}
Attachment: Javadoc generation method
# 使用 javadoc 命令生成 Javadoc 文档
➜ bin ./javadoc -public -sourcepath ./src -subpackages com -encoding utf-8 -charset utf-8 -d ./javadocout
# 使用 Java 18 的 jwebserver 把生成的 Javadoc 发布测试
➜ bin ./jwebserver -d /Users/darcy/develop/javadocout
Access test:
JEP 416: Reimplementing Reflection Core Functionality Using Method Handles
Java 18 improves the implementation logic of java.lang.reflect.Method
and Constructor
to make it perform better and faster. This change will not change the related API, which means that you can experience better performance reflection without changing the reflection-related code in development.
OpenJDK officially gives the reflection performance benchmark results of the new and old implementations.
Before Java 18:
Benchmark Mode Cnt Score Error Units
ReflectionSpeedBenchmark.constructorConst avgt 10 68.049 ± 0.872 ns/op
ReflectionSpeedBenchmark.constructorPoly avgt 10 94.132 ± 1.805 ns/op
ReflectionSpeedBenchmark.constructorVar avgt 10 64.543 ± 0.799 ns/op
ReflectionSpeedBenchmark.instanceFieldConst avgt 10 35.361 ± 0.492 ns/op
ReflectionSpeedBenchmark.instanceFieldPoly avgt 10 67.089 ± 3.288 ns/op
ReflectionSpeedBenchmark.instanceFieldVar avgt 10 35.745 ± 0.554 ns/op
ReflectionSpeedBenchmark.instanceMethodConst avgt 10 77.925 ± 2.026 ns/op
ReflectionSpeedBenchmark.instanceMethodPoly avgt 10 96.094 ± 2.269 ns/op
ReflectionSpeedBenchmark.instanceMethodVar avgt 10 80.002 ± 4.267 ns/op
ReflectionSpeedBenchmark.staticFieldConst avgt 10 33.442 ± 2.659 ns/op
ReflectionSpeedBenchmark.staticFieldPoly avgt 10 51.918 ± 1.522 ns/op
ReflectionSpeedBenchmark.staticFieldVar avgt 10 33.967 ± 0.451 ns/op
ReflectionSpeedBenchmark.staticMethodConst avgt 10 75.380 ± 1.660 ns/op
ReflectionSpeedBenchmark.staticMethodPoly avgt 10 93.553 ± 1.037 ns/op
ReflectionSpeedBenchmark.staticMethodVar avgt 10 76.728 ± 1.614 ns/op
New implementation in Java 18:
Benchmark Mode Cnt Score Error Units
ReflectionSpeedBenchmark.constructorConst avgt 10 32.392 ± 0.473 ns/op
ReflectionSpeedBenchmark.constructorPoly avgt 10 113.947 ± 1.205 ns/op
ReflectionSpeedBenchmark.constructorVar avgt 10 76.885 ± 1.128 ns/op
ReflectionSpeedBenchmark.instanceFieldConst avgt 10 18.569 ± 0.161 ns/op
ReflectionSpeedBenchmark.instanceFieldPoly avgt 10 98.671 ± 2.015 ns/op
ReflectionSpeedBenchmark.instanceFieldVar avgt 10 54.193 ± 3.510 ns/op
ReflectionSpeedBenchmark.instanceMethodConst avgt 10 33.421 ± 0.406 ns/op
ReflectionSpeedBenchmark.instanceMethodPoly avgt 10 109.129 ± 1.959 ns/op
ReflectionSpeedBenchmark.instanceMethodVar avgt 10 90.420 ± 2.187 ns/op
ReflectionSpeedBenchmark.staticFieldConst avgt 10 19.080 ± 0.179 ns/op
ReflectionSpeedBenchmark.staticFieldPoly avgt 10 92.130 ± 2.729 ns/op
ReflectionSpeedBenchmark.staticFieldVar avgt 10 53.899 ± 1.051 ns/op
ReflectionSpeedBenchmark.staticMethodConst avgt 10 35.907 ± 0.456 ns/op
ReflectionSpeedBenchmark.staticMethodPoly avgt 10 102.895 ± 1.604 ns/op
ReflectionSpeedBenchmark.staticMethodVar avgt 10 82.123 ± 0.629 ns/op
It can be seen that the performance is slightly better in some scenarios.
JEP 417: Vector API (Three Incubations)
A new API was introduced in Java 16 for vector computation, which can be reliably compiled at runtime to supported CPU architectures, enabling better computing power.
The Vector API performance has been improved in Java 17, with enhancements such as operations on characters, conversions between byte vectors and boolean arrays, and more.
Its performance will continue to be optimized in JDK 18 now.
JEP 418: Internet Address Resolution SPI
For the Internet Address Resolution SPI, define an SPI for host address and domain address resolution so that java.net.InetAddress
can use resolvers other than the platform's built-in resolvers.
InetAddress inetAddress = InetAddress.getByName("www.wdbyte.com");
System.out.println(inetAddress.getHostAddress());
// 输出
// 106.14.229.49
JEP 419: Foreign Function & Memory API (Second Incubation)
The new API allows Java developers to interact with code and data outside the JVM, by calling external functions, and calling native libraries without using JNI.
This is an incubation feature; need to add --add-modules jdk.incubator.foreign
to compile and run Java code, Java 18 improves the related API to make it easier to use.
history
- Java 14 JEP 370 (opens new window) introduced the External Memory Access API (Incubator).
- Java 15 JEP 383 (opens new window) introduced the External Memory Access API (second incubator).
- Java 16 JEP 389 (opens new window) introduced the External Linker API (Incubator).
- Java 16 JEP 393 (opens new window) introduced the External Memory Access API (third incubator).
- Java 17 JEP 412 (opens new window) introduced foreign functions and memory API (incubator).
JEP 420: Switch Expressions (Secondary Incubation)
Improvements to Switch have been underway since Java 17, and Java 17's JEP 406 has enhanced Switch expressions to reduce the amount of code.
Here are a few examples:
// JDK 17 以前
static String formatter(Object o) {
String formatted = "unknown";
if (o instanceof Integer i) {
formatted = String.format("int %d", i);
} else if (o instanceof Long l) {
formatted = String.format("long %d", l);
} else if (o instanceof Double d) {
formatted = String.format("double %f", d);
} else if (o instanceof String s) {
formatted = String.format("String %s", s);
}
return formatted;
}
After Java 17, it can be improved by writing the following:
// JDK 17 之后
static String formatterPatternSwitch(Object o) {
return switch (o) {
case Integer i -> String.format("int %d", i);
case Long l -> String.format("long %d", l);
case Double d -> String.format("double %f", d);
case String s -> String.format("String %s", s);
default -> o.toString();
};
}
switch can be combined with null
to judge:
static void testFooBar(String s) {
switch (s) {
case null -> System.out.println("Oops");
case "Foo", "Bar" -> System.out.println("Great");
default -> System.out.println("Ok");
}
}
Complex expressions can be added to case:
static void testTriangle(Shape s) {
switch (s) {
case Triangle t && (t.calculateArea() > 100) ->
System.out.println("Large triangle");
default ->
System.out.println("A shape, possibly a small triangle");
}
}
Type judgment can be performed in case:
sealed interface S permits A, B, C {}
final class A implements S {}
final class B implements S {}
record C(int i) implements S {} // Implicitly final
static int testSealedExhaustive(S s) {
return switch (s) {
case A a -> 1;
case B b -> 2;
case C c -> 3;
};
}
Extension: JEP 406: Type Matching for Switch (Preview)
JEP 421: Deprecation Removal Related
Finalization will be removed in the future, currently Finalization is still enabled by default, but can be disabled manually; in future releases, it will be disabled by default; in future releases, it will be removed. For resource management, try try-with-resources
or java.lang.ref.Cleaner
.
refer to
subscription
You can search for the programmer Alang on WeChat or visit the unread code blog to read.
This article has been included in Github.com/niumoo/JavaNotes , welcome to Star.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。