我正在使用固定大小的 Java 线程池(ExecutorService)。假设我向线程池提交了一个作业,并且该作业变得空闲。
是否有可能将空闲作业从线程池中删除,以便可以处理队列中的其他作业,然后再次添加空闲作业?
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javafx.concurrent.Task;
public class T {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Task t = new Task(){
@Override
protected Object call() throws Exception {
System.out.println(1/0);
return null;
}
};
//My progresss Bar in JavaFX
//Progressbar.progressProperty().bind(t.progressProperty());
Future future = executorService.submit(t);
try {
future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //returns null if …Run Code Online (Sandbox Code Playgroud) 的定义ExecutorService.newCachedThreadPool()是
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
Run Code Online (Sandbox Code Playgroud)
它正在创建一个带有 的池corePoolSize = 0,maximumPoolSize = Integer.MAX_VALUE以及一个无界队列。
然而在文档中它ThreadPoolExecutor说:
当在方法execute(java.lang.Runnable)中提交新任务并且运行的线程数少于corePoolSize时,即使其他工作线程处于空闲状态,也会创建一个新线程来处理该请求。如果运行的线程数超过 corePoolSize 但少于 maxPoolSize ,则仅当队列已满时才会创建新线程。
那么corePoolSize = 0在这种情况下是如何工作的呢?最初,有 0 个线程,因此尽管文档中没有说明,但我认为它将为提交的第一个任务创建一个新线程。但是,现在我们有 1 个线程 > corePoolSize = 0,并且 1 个线程 < MaximumPoolSize = Integer.MAX_VALUE,根据上面的文档“仅当队列已满时才会创建新线程”,但队列是无界的,所以不会再创建新线程,而我们只能使用 1 个线程?
java multithreading executorservice blockingqueue threadpoolexecutor
我想使用 Mockito 模拟以下代码片段。
Future<Optional<List<User>>> getUser =
executorService.submit(() -> userRepository.findById(user.getUserId()));
Run Code Online (Sandbox Code Playgroud)
我尝试过以下代码,但没有成功
@Mock
private ExecutorService executorService;
@Mock
private userRepository userRepository;
when(executorService.submit(() -> userRepository.findById(USER_ID)))
.thenReturn(ConcurrentUtils.constantFuture(userList));
Run Code Online (Sandbox Code Playgroud)
谁能给我解决这个问题吗?
这是我首先使用的代码,但在最新的 Android 版本中,AsyncTask类已被弃用,因此它没有响应,然后我使用了该类Thread,但该类也无法工作。我想要和我在课堂上得到的结果一样的结果AsyncTask。我知道我必须使用 java.util.concurrent 包的一些执行器类,但不知道哪个以及如何使用它。请帮我解决这件事。
private static final String USGS_REQUEST_URL =
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-05-02&minfelt=50&minmagnitude=5";
EarthquakeAsyncTask task = new EarthquakeAsyncTask();
task.execute(USGS_REQUEST_URL);
private class EarthquakeAsyncTask extends AsyncTask<String, Void, Event> {
@Override
protected Event doInBackground(String... urls) {
// Perform the HTTP request for earthquake data and process the response.
Event result = Utils.fetchEarthquakeData(urls[0]);
return result;
}
@Override
protected void onPostExecute(Event result) {
// Update the information displayed to the user.
updateUi(result);
}
}
Run Code Online (Sandbox Code Playgroud)
private static final String USGS_REQUEST_URL = …Run Code Online (Sandbox Code Playgroud) 我刚刚将 Spring Boot 应用程序升级到 Java 21。作为其中的一部分,我还进行了更改以使用虚拟线程。无论是在服务 API 请求时还是在使用执行器在内部执行异步操作时。
对于一种用例,由虚拟线程驱动的执行器的性能似乎比ForkJoinPool由操作系统线程驱动的执行器差。此用例是设置一些 MDC 值并通过 HTTP调用外部系统。
这是我的伪代码:
List<...> ... = executorService.submit(
() -> IntStream.rangeClosed(-from, to)
.mapToObj(i -> ...)
.parallel()
.map(... -> {
try {
service.setSomeThreadLocalString(...);
MDC.put(..., ...);
MDC.put(..., ...);
return service.call(...);
} finally {
service.removeSomeThreadLocalString(...);
MDC.remove(...);
MDC.remove(...);
}
})
.toList())
.get();
Run Code Online (Sandbox Code Playgroud)
其中 ExecutorService 是:
new ForkJoinPool(30)Executors.newVirtualThreadPerTaskExecutor()看起来选项 1 的性能比选项 2 好很多。有时它比选项 1 快 100%。我在 Java 21 环境中完成了这个测试。我正在测试 10 个并行执行。其中选项 1 通常需要 800-1000 毫秒,选项 2 通常需要 1500-2000 毫秒。
如果有任何区别,请在 Spring …
我正在尝试将代码从使用java 计时器移植到使用scheduledexecutorservice
我有以下用例
class A {
public boolean execute() {
try {
Timer t = new Timer();
t.schedule (new ATimerTask(), period, delay);
} catch (Exception e) {
return false;
}
}
}
class B {
public boolean execute() {
try {
Timer t = new Timer();
t.schedule (new BTimerTask(), period, delay);
} catch (Exception e) {
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该只使用ScheduledExecutorService替换A类和B类中的Timer实例,并将ATimerTask和BTimerTask类设置为Runnable类,例如
class B {
public boolean execute() {
try {
final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
scheduler.scheduleWithFixedDelay (new …Run Code Online (Sandbox Code Playgroud) 我是java并发的新手,所以这可能是一个已经回答很久或者太明显的问题,我可能会遗漏一些东西.
我像这样的任务运行:
Executors.newSingleThreadExecutor().执行(任务)
我的问题是当它结束执行任务的run方法时为什么它不退出或为什么线程仍然存活?我的理解是,一旦线程run()完成线程就不再存在了,对吧?
我不是多线程专家,但我看到我当前使用的代码存在一些性能问题ExecutorService.
我正在开发一个项目,在这个项目中,我需要对我的服务器进行HTTP URL调用,如果响应时间过长则会超时.目前它正在返回简单的JSON字符串..
我目前的要求是10 ms.在10 ms其中应该能够从服务器获取数据.我猜它是可能的,因为它只是对同一数据中心内的服务器的HTTP调用.
我的客户端程序和实际服务器在同一个数据中心内,并且ping时间延迟0.5 ms在它们之间,所以它应该是可行的.
我用RestTemplate它来进行URL调用.
下面是我为我写的代码,使用ExecutorService和Callables-
public class URLTest {
private ExecutorService executor = Executors.newFixedThreadPool(10);
public String getData() {
Future<String> future = executor.submit(new Task());
String response = null;
try {
System.out.println("Started..");
response = future.get(100, TimeUnit.MILLISECONDS);
System.out.println("Finished!");
} catch (TimeoutException e) {
System.out.println("Terminated!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我的Task类,它实现了Callable接口 …
java performance multithreading executorservice resttemplate
我看到一种行为,我无法解释
我有一个Runnable,它的代码是:
run()
{
print("start");
try{
doSomething();
print("end");
}catch (Exception e){
print("problem");
}
print("method end");
}
Run Code Online (Sandbox Code Playgroud)
这种行为很奇怪,因为我得到的唯一打印是"开始" - 我希望得到"问题"和"方法结束"打印.如果doSomething本身处理异常 - 那么将打印"end".但除了"开始",我没有得到任何印刷品
现在我知道doSomething方法存在一些问题,好像我不是通过执行程序服务运行它,我得到"Method Not Found"异常.
我认为它可能以某种方式连接到我使用的Executor服务 - Executors.newFixedThreadPool,但我无法解释它
谢谢你的建议!
executorservice ×10
java ×10
threadpool ×2
android ×1
concurrency ×1
exception ×1
executors ×1
java-21 ×1
javafx ×1
mockito ×1
performance ×1
resttemplate ×1
timer ×1
unit-testing ×1