我用play开发我的项目,嵌入netty3作为我的应用服务器 请检查以下测试代码:
package controllers;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.io.FileUtils;
import play.Logger;
import play.Play;
import play.mvc.Controller;
import play.mvc.results.RenderText;
public class Upload extends Controller {
private static Integer counter = 0;
private static final Integer MAX = 1;
public static void index() {
render("/upload.html");
}
public static void upload(File file) {
System.out.println("start " + Thread.currentThread());
synchronized (counter) {
System.out.println("middle " + Thread.currentThread());
if (counter > MAX) {
renderText("Sorry, the max upload thread is " + MAX);
} else {
counter++;
uploadFile(file);
counter--;
renderText("Upload success");
}
}
System.out.println("end " + Thread.currentThread());
}
static void uploadFile(File imgFile) {
File file = Play.getFile("/uploads");
try {
FileUtils.copyFileToDirectory(imgFile, file);
} catch (IOException e) {
Logger.error("upload file error", e);
}
}
}
当我同时打开两个浏览器(Firefox和Chrome)上传文件时,我在'upload(File file)'方法中调试了断点。但我发现只有 1 个线程正在处理。 之后,第二个请求就来了。
输出是:
start Thread[play-thread-1,5,main]
middle Thread[play-thread-1,5,main]
start Thread[play-thread-1,5,main]
middle Thread[play-thread-1,5,main]
但是在Tomcat/Jetty中,控制台有两个线程输出。
有没有人遇到过同样的问题?
最佳答案
我假设您在开发模式下运行?
play 文档说为了使调试更容易,默认情况下 Play 在开发模式下以单线程模型运行,在生产模式下它以 numbers_of_cores + 1
运行。
您可以在 application.conf 中覆盖它。
# example of using a thread pool of 3
play.pool=3
关于multithreading - 为什么play(netty3)上传使用单线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8076979/