【问题标题】:Is it possible to create a new thread in a @RequestScope bean是否可以在 @RequestScope bean 中创建一个新线程
【发布时间】:2019-05-23 22:24:57
【问题描述】:

我正在处理一个使用@RequestScope 注释的服务类,问题是有一种方法需要很长时间才能继续,我想知道是否可以在其中的哪个部分创建新线程代码将被执行。

我尝试过使用 ManagedExecutorService、CompletableFuture.runAsync(()) 和一个简单的线程,但它们似乎都不起作用?

@RequestScoped
public class OfferService 

以及方法:

  public List<DTO> createLocation(List<DTO> locationAdressDTOS) {
        List<DTO> lokationLookupList ;

        locationLookupList = offerDao.createMarktlokation(DTOS.get(0).getOfferNo(), DTOS);

        DTOS.forEach(malo -> {
            if (BooleanUtils.isTrue(malo.isShouldUploadHistoricalData()) && malo.getProcessId() != null) {
                callHistoricalDataUpload(malo.getOfferNo(), malo.getProcessId());
            }
        });
        return lokationLookupList;
    }

我希望 if 部分异步运行? //

 callHistoricalDataUpload(malo.getOfferNo(), malo.getProcessId());

我认为它不起作用的原因是因为该类使用@RequestScope 进行了注释,并且在它返回之后响应被破坏并且它也是上下文? 当我尝试简单地创建一个新线程时:

2019-05-23 14:45:31,934 ERROR [stderr] (Thread-225) Exception in thread "Thread-225" org.jboss.weld.context.ContextNotActiveException: WELD-001303: No active contexts for scope type javax.enterprise.context.RequestScoped

我尝试过的:

CompletableFuture.runAsync(() -> {
            try {
                this.uploadHistoricalData(offerNo, processId);
            } catch (DatatypeConfigurationException | ParseException e) {
                logger.severe(e.getMessage());
            }
        });


        managedExecutorService.execute(() -> {
            try {
                this.uploadHistoricalData(offerNo, processId);

            } catch (DatatypeConfigurationException | ParseException e) {
                logger.severe(e.getMessage());
            }
        });


        new Thread((() -> {
            try {

                this.uploadHistoricalData(offerNo, processId);

            } catch (DatatypeConfigurationException | ParseException e) {
                logger.severe(e.getMessage());
            }
        })).start();

这些都没有用

【问题讨论】:

  • 您可以创建一个简单的线程来执行某些操作。
  • 你能告诉我们产生错误的代码吗?它似乎缺少您提到的线程创建。
  • @ÁlexSantanaFogaça 我刚刚编辑了帖子,你可以看看:)

标签: java asynchronous jboss wildfly jakarta-ee


【解决方案1】:

看来你的问题和这个other question on StackOverflow一样。

这是因为请求与处理请求的服务器线程相关联。当您切换线程时,将无法再访问该请求上下文。

您可能不需要 @RequestScoped 注释。

【讨论】:

  • 很遗憾,我无法删除此注释。是否可以将请求上下文传播到新线程?
  • 是的。您可以收集之前需要的数据,然后在异步调用中使用它。
  • 在这个thread about propagating the request scope to an asynchronous task 上有一个解决方案,但取决于你的情况。
  • 这是一个依赖于弹簧的解决方案
  • 对不起,我的错误。我找到了这个other solution,看起来很简洁。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
相关资源
最近更新 更多