ThreadPoolExecutor com ArrayBlockingQueue
Eu comecei a ler mais sobre ThreadPoolExecutor do Java Doc como eu estou usando em um dos meus projetos. Então, alguém pode me explicar o que essa linha significa realmente? - Eu sei o que cada parâmetro representa, mas eu queria entendê-lo de maneira mais geral / leiga de alguns dos especialistas aqui.
ExecutorService service = new ThreadPoolExecutor(10, 10, 1000L,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10, true), new
ThreadPoolExecutor.CallerRunsPolicy());
Atualizada:- Declaração do problema é: -
Cada thread usa um ID exclusivo entre 1 e 1000 e o programa tem que ser executado por 60 minutos ou mais. Então, nesses 60 minutos, é possível que todos os IDs sejam finalizados, então eu preciso reutilizar esses ID's novamente. Então este é o programa abaixo que eu escrevi usando o executor acima.
class IdPool {
private final LinkedList<Integer> availableExistingIds = new LinkedList<Integer>();
public IdPool() {
for (int i = 1; i <= 1000; i++) {
availableExistingIds.add(i);
}
}
public synchronized Integer getExistingId() {
return availableExistingIds.removeFirst();
}
public synchronized void releaseExistingId(Integer id) {
availableExistingIds.add(id);
}
}
class ThreadNewTask implements Runnable {
private IdPool idPool;
public ThreadNewTask(IdPool idPool) {
this.idPool = idPool;
}
public void run() {
Integer id = idPool.getExistingId();
someMethod(id);
idPool.releaseExistingId(id);
}
// This method needs to be synchronized or not?
private synchronized void someMethod(Integer id) {
System.out.println("Task: " +id);
// and do other calcuations whatever you need to do in your program
}
}
public class TestingPool {
public static void main(String[] args) throws InterruptedException {
int size = 10;
int durationOfRun = 60;
IdPool idPool = new IdPool();
// create thread pool with given size
ExecutorService service = new ThreadPoolExecutor(size, size, 500L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(size), new ThreadPoolExecutor.CallerRunsPolicy());
// queue some tasks
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun * 60 * 1000L);
// Running it for 60 minutes
while(System.currentTimeMillis() <= endTime) {
service.submit(new ThreadNewTask(idPool));
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
Minhas perguntas é: - Este código está certo, tanto quanto o desempenho é considerado ou não? E o que mais eu posso fazer aqui para torná-lo mais preciso? Qualquer ajuda será apreciada.