【问题标题】:How to initialise a thread-local with type Map using ThreadLocal.withInitial?如何使用 ThreadLocal.withInitial 初始化类型为 Map 的线程本地?
【发布时间】:2019-01-04 15:38:45
【问题描述】:

我正在尝试使用“ThreadLocal.withInital”方法初始化 Map 类型的线程本地

我可以继续设置一个新的 ThreadLocal 并添加一个 setter 方法来继续初始化。但我正在尝试寻找一种方法是否可以通过初始来完成。

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = new ThreadLocal<>();

预期输出:

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(<Hash-map that is set with a predefined date and a boolean>)

【问题讨论】:

    标签: java initialization thread-local


    【解决方案1】:

    也许是这样的:

    private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(() -> {
            Map<Date, Boolean> map = new HashMap<>();
            map.put(new Date(), true);
            //do other stuff...
            return map;
        });
    

    【讨论】:

    • 谢谢建议,这个语句lambda可以换成表达式lambda吗?
    • 表达式 lambda 是什么意思?您在寻找单线解决方案吗?
    • 是的,当我这样做时: ThreadLocal.withInitial(() -> { return new HashMap(){{ put(new Date(), true); }} ; }); IntelliJ 建议可以将其转换为表达式 lambda。
    • 考虑 Map 有一个 putAll 方法,但它需要另一个 Map 作为输入。还要考虑到这样代码会变得不可读,我认为有时最好保持可读性。此外,这样做不会有任何性能改进。
    • 足够公平。感谢您的建议。
    【解决方案2】:

    ThreadLocal.withInitial 方法接受一个 Functional 参数,所以它可以是一个 Lambda,像这样:

    private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(() -> {
        Map<Date, Boolean> map = new HashMap<>();
        map.put(new Date(), true);
        return map;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 2012-02-22
      • 2023-03-18
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多