Ensure that code within CompletableFuture callback executes after

◇◆丶佛笑我妖孽 提交于 2019-12-30 07:47:08

问题


Say I have this:

public void foo(){
     CompletableFuture.delayedExecutor(1, TimeUnit.MILLISECONDS).execute(() -> {                 
         doSomethingA();                
      });       
      doSomethingB();        
}

Is there any guarantee that doSomethingB(); will always run before doSomethingA();? Something tells me with thread pre-emption, it's possible, although unlikely, that doSomethingA() could be run first?


回答1:


No, there is no guarantee, when on a machine which has multiple processors, that doSomethingB() would always execute before doSomethingA(). Though it will likely happen 99.999999999% of the time.

I noticed in some of your comments a reference to an "Event Loop". In Java there is no native concept of an Event Loop like there is in, say, Node and Javascript. If you have 4 threads, with four processors, and you submit four tasks, all four tasks will run in parallel.



来源:https://stackoverflow.com/questions/54560757/ensure-that-code-within-completablefuture-callback-executes-after

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!