empecé a leer más sobre ThreadPoolExecutor desde Java Doc como lo estoy usando en una de mi proyecto. Entonces, ¿alguien puede explicarme qué significa realmente esta línea? Sé lo que significa cada parámetro, pero quería entenderlo de una manera más general/laica de algunos de los expertos aquí.ThreadPoolExecutor con ArrayBlockingQueue
ExecutorService service = new ThreadPoolExecutor(10, 10, 1000L,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10, true), new
ThreadPoolExecutor.CallerRunsPolicy());
Actualizado: - Planteamiento del problema es: -
Cada hilo utiliza el ID único entre 1 y 1000 y el programa tiene que correr durante 60 minutos o más, así que en ese 60 minutos es posible que todos los ID se terminen, así que necesito reutilizar esos ID nuevamente. Así que este es el programa a continuación que escribí usando el ejecutor anterior.
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);
}
}
Mi pregunta es: - Este código es correcto por lo que el rendimiento se considera o no? ¿Y qué más puedo hacer aquí para hacerlo más preciso? Cualquier ayuda será apreciada.
No veo nada malo en su código, con excepción quizá de tener un try/finally en su método de "correr" para asegurarse de que ID siempre ha ser liberado (para cuando usted tiene un código más complicado en "algunMetodo "). – Matt
@Matt, gracias por comentar, ¿entonces algúnMétodo tiene que estar sincronizado? ¿o no? Como en mi caso, lo hice sincronizado. – ferhan
Y 'idPool.releaseExistingId (id);' debería aparecer en el bloque finally ¿no? – ferhan