简体   繁体   English

在 ConcurrentMap 中填充条目<string, completablefuture<object> &gt; 在 java</string,>

[英]Populating entries in ConcurrentMap<String, CompletableFuture<Object>> in java

I am starting with the concept of CompletableFuture in java.我从 java 中的CompletableFuture概念开始。 I have a use case where I need to populate a values in Map<String, CompletableFuture<Object>> .我有一个用例,我需要在Map<String, CompletableFuture<Object>>中填充一个值。

Assuming there is a Student entity class and a ConcurrentMap<String, CompletableFuture<Student>> .假设有一个 Student 实体 class 和一个ConcurrentMap<String, CompletableFuture<Student>> I tried to populate student entries into the map in following way:我尝试通过以下方式将学生条目填充到 map 中:

Student student = new Student();
ConcurrentMap<String, CompletableFuture<Student>> studentMap = new ConcurrentMap<>();

CompletableFuture<Student> studentcf = new CompletableFuture<>();
studentcf.complete(student); // Not sure whether it is the right way to convert a entity into CompletableFuture

studentMap.put("Alex", studentcf);

The above solution worked but I am not sure whether it is the right way to do this (converting the entity to CompletableFuture).上述解决方案有效,但我不确定这是否是正确的方法(将实体转换为 CompletableFuture)。 Can someone please suggest me the right way to do the above scenario?有人可以建议我做上述情况的正确方法吗?

Any suggestions will be helpful!!任何建议都会有所帮助!! Thanks in advance!!提前致谢!!

The above code is possible, but it doesn't make much sense.上面的代码是可以的,但是没有多大意义。 CompletableFuture is used for asynchronous calls. CompletableFuture用于异步调用。 When the result of an operation is not known immediately, but only after some time.当一个操作的结果不是立即知道的,而是在一段时间后才知道的。

Example:例子:

    public Future<Student> calculateAsync() throws InterruptedException {
        CompletableFuture<Student> completableFuture 
          = new CompletableFuture<>();
     
        Executors.newCachedThreadPool().submit(() -> {
            Thread.sleep(5000);
            Student student = new Student();
            completableFuture.complete(student); //completed after 5 seconds
            return null;
        });
     
        return completableFuture; //return immediately
    }
    
    Future<Student> completableFuture = calculateAsync();
     
    // ... 
     
    Student result = completableFuture.get(); //This call is blocked until the result, which is generated by the embedded thread, is known.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM