java - 在 AppEngine 标准环境中使用 java 创建线程

标签 java multithreading google-app-engine task-queue

我是 Google Cloud Platform 的新用户。我正在使用 AppEngine 标准环境。我需要在 java 中创建线程,但我认为这是不可能的,是吗?

情况如下:

我需要为用户创建Feed

共有三个数据库,名称分别为d1、d2、d3

每当用户发送提要请求时,Java 都会创建三个线程,每个线程对应一个数据库。例如t1代表d1,t2代表d2,t3代表d3。这些线程必须异步运行以获得更好的性能,然后将这 3 个线程的数据组合起来并在响应中发送回用户。

我知道如何为此编写代码,但正如您所知,我需要线程来完成这项工作。如果 AppEngine 标准环境。不允许那我该怎么办?还有其他办法吗?

在 GCP 文档中,他们说:

To avoid using threads, consider Task Queues

我读到了有关任务队列的内容。队列有两种类型:推式队列和拉式队列。两者都是异步运行的,但它们不会将响应发送回用户。我认为它们只是为了在后台完成任务而设计的。

您能告诉我如何实现我的目标吗?为此我需要学习哪些东西?

最佳答案

注意:答案仅基于文档,我不是 java 用户。

标准环境支持线程,但有限制。来自 Threads :

Caution: Threads are a powerful feature that are full of surprises. To learn more about using threads with Java, we recommend Goetz, Java Concurrency in Practice.

A Java application can create a new thread, but there are some restrictions on how to do it. These threads can't "outlive" the request that creates them.

An application can

  • Implement java.lang.Runnable.
  • Create a thread factory by calling com.google.appengine.api.ThreadManager.currentRequestThreadFactory().
  • Call the factory's newRequestThread method, passing in the Runnable, newRequestThread(runnable), or use the factory object returned by com.google.appengine.api.ThreadManager.currentRequestThreadFactory() with an ExecutorService (e.g., call Executors.newCachedThreadPool(factory)).

However, you must use one of the methods on ThreadManager to create your threads. You cannot invoke new Thread() yourself or use the default thread factory.

An application can perform operations against the current thread, such as thread.interrupt().

Each request is limited to 50 concurrent request threads. The Java runtime will throw a java.lang.IllegalStateException if you try to create more than 50 threads in a single request.

When using threads, use high level concurrency objects, such as Executor and Runnable. Those take care of many of the subtle but important details of concurrency like Interrupts and scheduling and bookkeeping.

关于java - 在 AppEngine 标准环境中使用 java 创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46678963/

相关文章:

java - 如何从 Google Datastore(Java 中)删除特定记录?

java - 无法根据 Android Studio 中的加速度计数据更新应用程序

java - 当自定义绘画代码在另一个类中时不执行自定义绘画

multithreading - 如何重置多线程任务? (JX核心)

c# - Web 应用程序中的异步等待性能

jquery - 从 GAE Python 中的 AJAX 调用获取响应时出现问题

java - Gitlab ci selenium testing with docker not connecting to RemoteWebDriver

Java:如何合并对象

java - java多线程程序中的Volatile变量

google-app-engine - 通过代理使用 Google App Engine 的位置服务