小编Gau*_*m M的帖子

ForkJoinPool 调度 vs ExecutorService

我对ExecutorService和 的内部调度机制有点困惑ForkJoinPool

我了解ExecutorService调度是通过这种方式完成的。

一堆任务在排队。一旦线程可用,它将处理第一个可用任务,依此类推。

同时, aForkJoinPool被表示为不同的,因为它使用了工作窃取算法。如果我理解正确,这意味着一个线程可以从另一个线程窃取一些任务。

然而,我并不真正理解在ExecutorService和 中实现的机制之间的区别ForkJoinPool。根据我的理解,这两种机制都应该尽可能减少每个线程的空闲时间。

我会理解,如果在 a 的情况下ExecutorService,每个线程都有自己的队列。然而,情况并非如此,因为队列由池的不同线程共享......

任何澄清将是非常受欢迎的!

java executorservice forkjoinpool

9
推荐指数
1
解决办法
1640
查看次数

'filter()' 和 'map()' 可以互换

我有一个简单的流,如下所示:

List<Long> r = l.stream()
                .filter(a->a.getB() % 2 == 0)
                .map(A::getB)
                .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但 Intellij 建议我:

'filter()' 和 'map()' 可以交换检查信息:报告可以简化的流 API 调用链。它允许在遍历集合时避免创建冗余的临时对象。例如

  • collection.stream().forEach() ?集合.forEach()
  • collection.stream().collect(toList/toSet/toCollection()) ? 新的集合类型<>(集合)

Intellij 给出的例子很容易理解,但我不明白为什么它建议我map().filter().

我查看了来源ReferencePipeline但没有发现任何线索:map().filter()或者filter().map()在与流实现相关的临时对象方面没有区别(filter().map()如果A.b是一个让我更加困惑的原语,那么自动装箱会更少)。

那么,我是否缺少流实现的某些点,或者这是 Intellij 的误报?

java intellij-idea java-stream

6
推荐指数
1
解决办法
440
查看次数

Stream.parallel() 不是更新了spliterator 的特性吗?

这个问题是基于这个问题的答案Stream.of 和 IntStream.range 有什么区别?

由于IntStream.range产生了一个已经排序的流,下面代码的输出只会生成如下输出0

IntStream.range(0, 4)
         .peek(e -> System.out.println(e))
         .sorted()
         .findFirst();
Run Code Online (Sandbox Code Playgroud)

分离器也将具有SORTED特性。下面的代码返回true

System.out.println(
    IntStream.range(0, 4)
             .spliterator()
             .hasCharacteristics(Spliterator.SORTED)
);
Run Code Online (Sandbox Code Playgroud)

现在,如果我parallel()在第一个代码中引入 a ,那么正如预期的那样,输出将包含从0to 的所有 4 个数字,3但顺序是随机的,因为由于parallel().

IntStream.range(0, 4)
         .parallel()
         .peek(e -> System.out.println(e))
         .sorted()
         .findFirst();
Run Code Online (Sandbox Code Playgroud)

这将按任何顺序产生如下所示的内容:

2
0
1
3
Run Code Online (Sandbox Code Playgroud)

因此,我预计该SORTED属性已因parallel(). 但是,下面的代码true也会返回。

2
0
1
3
Run Code Online (Sandbox Code Playgroud)

为什么不parallel()改变SORTED属性?并且由于所有四个数字都被打印出来,Java 如何意识到即使该SORTED属性仍然存在,流也没有排序?

java java-stream

6
推荐指数
1
解决办法
131
查看次数

如何计算字符串中的括号?

这是我计算字符串中括号数量的方法。

public int checkParenthesis(String print, char par){
    int num = 0;
    for(int i = 0; i<print.length(); i++){
        if(print.indexOf(i) == par){
            num++;
        }
    }
    return num;
}
Run Code Online (Sandbox Code Playgroud)

它不起作用。它返回 0。 print是一个随机字符串,par是一个括号。

java string char

5
推荐指数
1
解决办法
146
查看次数

如何引用内部类成员的泛型类型?

我很想知道为什么testInnerClass编译失败,引用:

不兼容的类型:对象无法转换为字符串。

import java.util.List;

class Test<
        I extends Test.InnerClass,
        S extends Test.StaticInnerClass,
        O extends OtherClass> {

    void testOtherClass(O other) {
        String firstString = other.strings.get(0); //this works
    }
    
    void testStaticInnerClass(S staticInner) {
        String firstString = staticInner.strings.get(0); //this works
    }
    
    void testInnerClass(I inner) {
        String firstString = inner.strings.get(0); //this fails:
        //"incompatible types: Object cannot be converted to String" 
    }

    static class StaticInnerClass {
        List<String> strings;
    }
    
    class InnerClass {
        List<String> strings;
    }
}

class OtherClass {
    List<String> strings;
}
Run Code Online (Sandbox Code Playgroud)

testStaticInnerClass …

java generics nested inner-classes type-erasure

5
推荐指数
1
解决办法
57
查看次数

如何配置 MapStruct 在枚举值无法映射时抛出异常

这是我的映射器:

@Mapper
public interface ProductMapper {
    ProductClassification toProductClassification(ProductTypes pisType);
}
Run Code Online (Sandbox Code Playgroud)

其中ProductTypesProductClassification是枚举。我希望它在无法映射枚举时抛出异常,但出现编译器错误: The following constants from the source enum have no corresponding constant in the target enum and must be be mapped via adding additional mappings: EXTERNAL, UNKNOWN.

我尝试使用@ValueMappings注释,但只能将其配置为将值设置为 null,这是不够的:

@ValueMappings({
    @ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.NULL)
})
Run Code Online (Sandbox Code Playgroud)

将 MapStruct 映射器配置为在无法映射枚举常量时抛出异常的正确方法是什么?

java enums mapstruct

5
推荐指数
1
解决办法
7528
查看次数

哪种用法是首选 Enum.values() 或 Enum.class.getEnumConstants()?

要获取enum某种Enum类型的常量数组TestEnum,我们有两个选项 -TestEnum.values()TestEnum.class.getEnumConstants()。当我查看代码时,我可以看到getEnumConstants()正在values()通过反射调用该方法,然后将其缓存以备将来使用。在返回之前,数组也被克隆。

从下面的问题及其答案(仅关注性能)来看,性能似乎没有太大差异。

枚举 values() 方法和 class.getEnumConstants() 的比较

我想知道这些方法中的一种是否比另一种更受欢迎。我能想到的一个场景是创建一个适用于泛型的方法时,我们将泛型enum类作为参数传递。

<E extends Enum<E>> void doSomething(Class<E> clazz){
    for(E type : clazz.getEnumConstants()){
        // do something...
    }
}
Run Code Online (Sandbox Code Playgroud)

在上述情况下,我们只能使用该getEnumConstants方法。

还有其他类似的场景吗?如果我确定要使用的类型enum,那么使用values()方法不是更好吗?

java reflection enums

3
推荐指数
1
解决办法
75
查看次数

将给定日期与给定时区中没有时间部分的当前日期进行比较的最佳方法

我的要求是将给定时区中特定格式的给定日期与同一时区中的当前日期进行比较。此外,在比较时,我必须忽略时区。比较结果应该是:0 or 1 or -1

我尝试过的一种方法是

  1. 设置所需的时区
  2. 使用“new Date()”获取当前日期 使用“yyyy-MM-dd”格式化它,然后再次解析它以获取日期对象
  3. 对提供的日期字符串使用相同的格式化程序进行比较
  4. 然后使用 compareTo 比较两个日期,得到所需的结果
public void compareDate(){

    TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
    Date todayDate = dateFormatter.parse(dateFormatter.format(new Date()));
    Date date = dateFormatter.parse("2021-02-28");
    System.out.println(todayDate.compareTo(date));

}
Run Code Online (Sandbox Code Playgroud)

但以上对我来说看起来效率低下。

其他方法可能是获取如下所示的两个日期然后进行比较?

public static Date getDateWithoutTimeUsingCalendar() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}
Run Code Online (Sandbox Code Playgroud)

有人可以建议一个更好的选择吗?

只有一件事,时区和没有时间的比较必须在那里。

java datetime date

3
推荐指数
1
解决办法
96
查看次数

IntStream.iterate 与要添加的交替值

我想创建一个整数序列,最好是一个IntStream遵循特定条件的 。一些简单的例子来解释我想要做什么:

从 0 开始的前 10 个偶数的序列(这里我没有问题,我用下面的代码片段来做)

IntStream.iterate(0, i -> i + 2).limit(10); 

//0,2,4,6,8,10,12,14,16,18
Run Code Online (Sandbox Code Playgroud)

前 10 个数字从 0 开始的序列,交替添加 2 和 3 到原始数字;所需的输出:

 //0,2,5,7,10,12,15,17,20,22
Run Code Online (Sandbox Code Playgroud)

我很愿意也使用了此方案 IntStream.iterate()还是IntStream.generate(),但不能让它在我自己的。我正在使用经典的 for 循环,它可以工作,但对于这样一个相对简单的任务来说有点长

List<Integer> list = new ArrayList<>();
list.add(0);
for(int i = 1, j = 1; i < 10; i++, j *= -1){
    if(j > 0){
        list.add(list.get(i-1) + 2);
    }
    else{
        list.add(list.get(i-1) + 3);
    }
}

//and then stream over the list to get IntStream
list.stream().mapToInt(Integer::intValue);
Run Code Online (Sandbox Code Playgroud)

使用IntStream.iterate()或实现与上述相同的任何简单方法 IntStream.generate() …

java sequence java-8 java-stream

3
推荐指数
1
解决办法
84
查看次数

不同测试类中使用的通用注解

@BeforeTest我有一个关于or之类的注释的问题@BeforeMethod。是否可以设置全局注释,以便我的所有测试类都将使用它们?我的框架中有 20 多个测试类,其中有很多测试方法。每个测试类都有类似@BeforeTest或 的先决条件@BeforeMethod,但对于每个测试类,此先决条件是相同的。所以我认为这可能是一个好主意,编写一个通用的注释方法,可以在每个测试类中使用。

java testng annotations testng-annotation-test

3
推荐指数
1
解决办法
171
查看次数