Per-key blocking Map in Java

后端 未结 3 1426
孤城傲影
孤城傲影 2021-02-07 23:02

I\'m dealing with some third-party library code that involves creating expensive objects and caching them in a Map. The existing implementation is something like

3条回答
  •  眼角桃花
    2021-02-07 23:41

    You can use funtom-java-utils - PerKeySynchronizedExecutor.

    It will create a lock for each key but will clear it for you immediately when it becomes unused.

    It will also grantee memory visibility between invocations with the same key, and is designed to be very fast and minimize the contention between invocations off different keys.

    Declare it in your class:

    final PerKeySynchronizedExecutor executor = new PerKeySynchronizedExecutor<>();
    

    Use it:

    Foo foo = executor.execute(key, () -> createFooExpensively());
    

提交回复
热议问题