Convert scala future to java future

后端 未结 3 2268
迷失自我
迷失自我 2021-02-19 09:18

I have a generated java interface containing a method:

public Future getCustomersAsync(AsyncHandler asyncHandler);

I w

3条回答
  •  被撕碎了的回忆
    2021-02-19 09:59

    Well its not practical to convert them, because scala Future do not provide functionality to interrupt or any other mechanism for cancellation. So there is no direct full-proof way to cancel a future via interruption or otherwise via method call in Future.

    So the simplest solution can be if cancellation is not desired would be:

      def convert[T](x:Future[T]):java.util.concurrent.Future[T]={
        new concurrent.Future[T] {
          override def isCancelled: Boolean = throw new UnsupportedOperationException
    
          override def get(): T = Await.result(x, Duration.Inf)
    
          override def get(timeout: Long, unit: TimeUnit): T = Await.result(x, Duration.create(timeout, unit))
    
          override def cancel(mayInterruptIfRunning: Boolean): Boolean = throw new UnsupportedOperationException
    
          override def isDone: Boolean = x.isCompleted
        }
      }
    

    But in case if you still need cancel, a handicapped fix would be as shown

    here. But I wouldn't recommend it though as its shaky

提交回复
热议问题