博文

目前显示的是 2019的博文

PHP8 —— New String Helpers

新增了三个字符串函数,str_starts_with, str_ends_with, str_contains, PHP 的函数这么方便,很难想象竟然一直没有这几个。 str_starts_with 判断字符串是否以另一个字符串开头,在PHP7以及之前 $id = 'inv_abcdefgh'; $result = strpos($id, 'inv_') === 0; var_dump($result); // true PHP8 中可以直接这么写 $result = str_starts_with($id, 'inv_'); str_ends_with 判断字符串是否以另外一个字符串结尾,在 PHP7 及之前,比较麻烦,通常是这么写 $id = 'abcd_inv'; $result = strpos(strrev($id), strrev('_inv')) === 0; 或者 $result = substr($id, -1 * strlen('_inv')) === '_inv'; 或者上正则吧 $result = preg_match('/_inv$/', $id) === 1; 看起来都是比较麻烦的。PHP8 里面可以简化成下面这样了 $id = 'abcd_inv'; $result = str_ends_with($id, '_ind'); str_contains 字符串包含,PHP8 之前一般就是 strpos 来实现了 $url = 'https://example?for=bar'; $result = strpos($url, '?') !== FALSE; PHP8 就直接一点 $result = str_contains($url, '?');

Java memory model and happens-before rules

Why define the Java memory model? Most modern computer architectures use a symmetric multiprocessor architecture. Each processor has an independent register set and cache, and multiple processors can execute different threads in the same process at the same time. This is called processor out-of-order execution. In Java, different threads may access the same shared or shared variable. If the compiler or processor is allowed to optimize these accesses, it is likely that an unthinkable problem will occur, which is referred to as compiler reordering. In addition to out-of-order execution of processors, reordering of compilers, and reordering of memory systems. Therefore, the Java language specification introduces the Java memory model, which restricts the compiler and processor by defining multiple rules, mainly for visibility and order. Three basic principles: atomicity, visibility, and orderliness. The Java memory model involves several keywords: locks, volatile fields, final modifi

Java 学习笔记 —— 创建Stream

可以使用如下方法创建Stream: 1)在Stream界面中使用静态工厂方法, 2)Iterable或Arrays上的流方法。 在Stream 接口中使用静态工厂方法 Java 8中新的 java.util.stream.Stream 接口提供了几种用于创建流的静态方法。 具体来说,我们可以使用静态方法 Stream.of , Stream.iterate 和 Stream.generate 。 static <T> Stream<T> of(T... values) 标准库中of方法的实现实际上委托给Arrays类中的stream方法 @SafeVarargs public static<T> Stream<T> of(T... values) { return Arrays.stream(values); } 例子: String days = Stream.of("monday", "tuesday", "wednesday") .collect(Collectors.joining(",")); System.out.println(days); // prints monday,tuesday,wednesday static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) 根据Javadocs,此方法“返回通过将函数f迭代应用到初始元素种子而生成的无限、有序的Stream”。 List<BigDecimal> nums = Stream.iterate(BigDecimal.ONE, n -> n.add(BigDecimal.ONE) ) .limit(10) .collect(Collectors.toList()); System.out.println(nums); // prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Stream.iterate(LocalDate.now(), ld ->