Skip to content

Instantly share code, notes, and snippets.

@sunzsh
Last active December 28, 2022 09:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunzsh/80cf4eb0675385084f828dda4570baf5 to your computer and use it in GitHub Desktop.
Save sunzsh/80cf4eb0675385084f828dda4570baf5 to your computer and use it in GitHub Desktop.
Java仿Js实现Promise.all实现并行处理的能力
package com.example.demo.util;
import java.util.concurrent.*;
public class Promise {
// 根据实际情况配置线程池
static ExecutorService threadPool = new ThreadPoolExecutor(10, 40, 20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
public static void allAwait(Runnable ...runnables) throws InterruptedException {
CountDownLatch checkFinish = new CountDownLatch(runnables.length);
for (Runnable runnable : runnables) {
threadPool.execute(()->{
try {
runnable.run();
} catch(Throwable e) {
e.printStackTrace();
} finally {
checkFinish.countDown();
}
});
}
checkFinish.await();
}
public static void all(Runnable ...runnables){
for (Runnable runnable : runnables) {
threadPool.execute(runnable);
}
}
}
@sunzsh
Copy link
Author

sunzsh commented Dec 28, 2022

SpringSecurity默认在子线程中无法获取到用户信息,需要配置:
https://stackoverflow.com/questions/3467918/how-to-set-up-spring-security-securitycontextholder-strategy

import javax.annotation.PostConstruct;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;

@Configuration
public class SecurityConfig {

  @PostConstruct
  public void enableAuthCtxOnSpawnedThreads() {
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment