简体   繁体   English

当第三方库请求ExecutorService时,请使用Scala ExecutionContext

[英]Use Scala ExecutionContext when 3rd Party Library asks for ExecutorService

I am using Play Framework (Scala version) with the Amazon AWS Java SDK to integrate Amazon S3 into an application. 我正在使用Play Framework(Scala版本)和Amazon AWS Java SDK将Amazon S3集成到应用程序中。

The AWS SDK has a TransferManager class that provides an abstraction to manage a thread pool for handling download/uploads to S3. AWS开发工具包有一个TransferManager类,它提供了一个抽象来管理线程池,以处理下载/上传到S3。

I am trying to determine if it is possible to integrate the core support Play has for custom ExecutionContexts into this object provided by the SDK. 我试图确定是否可以将自定义ExecutionContexts的核心支持Play集成到SDK提供的此对象中。 In particular, when instantiating the TransferManager provided by the AWS SDK, you can supply a custom ExecutorService as an optional parameter. 特别是,在实例化AWS SDK提供的TransferManager时,您可以提供自定义ExecutorService作为可选参数。

Scala's ExecutionClass binds the ExecutorService class via the "with" keyword in its class declaration, so I am wondering if there is some mechanism to get an ExecutorService object from the ExecutionContext like a method that transforms ExecutionContext => ExecutorService. Scala的ExecutionClass通过其类声明中的“with”关键字绑定ExecutorService类,所以我想知道是否有一些机制从ExecutionContext获取ExecutorService对象,就像转换ExecutionContext => ExecutorService的方法一样。

If not, is there any other approach? 如果没有,还有其他办法吗? At the moment I am just instantiating a custom ExecutorService directly in a class outside of Play's standard approach which is outlined here: 目前我只是在Play的标准方法之外的类中直接实例化自定义ExecutorService,这里概述了:

https://www.playframework.com/documentation/2.3.x/ThreadPools https://www.playframework.com/documentation/2.3.x/ThreadPools

This feels messy and against the conventions provided by the framework. 这感觉很麻烦,违反了框架提供的惯例。

Thanks for your time. 谢谢你的时间。

If you create your context like this (do not copy-paste this blindly - it's configured for blocking operations): 如果你像这样创建你的上下文(不要盲目地复制粘贴 - 它被配置为阻塞操作):

val blockingContext: ExecutionContext = {
    val executor = new ThreadPoolExecutor(100, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue(1000))
    executor.allowCoreThreadTimeOut(true)
    ExecutionContext.fromExecutorService(executor) // main part
}

Then you will be able to get ExecutorService instance from it: 然后,您将能够从中获取ExecutorService实例:

val executor: ExecutorService = blockingContext.prepare().asInstanceOf[ExecutorService]

Some implementations of ExecutionContext implement the ExecutionContextExecutorService trait, which is a sub-interface of both ExecutionContext and ExecutorService. ExecutionContext的一些实现实现ExecutionContextExecutorService trait,它是ExecutionContext和ExecutorService的子接口。 You might check to see if the ExecutionContext you get from Play/Akka is one of those. 您可以检查您从Play / Akka获得的ExecutionContext是否是其中之一。

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

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