ThreadPoolExecutor z ArrayBlockingQueue
Zacząłem czytać więcej o ThreadPoolExecutor z Java Doc, ponieważ używam go w jednym z moich projektów. Czy więc ktoś może mi wyjaśnić, co właściwie oznacza ta linia? - Wiem, co oznacza każdy parametr, ale chciałem to zrozumieć w sposób bardziej ogólny / zrozumiały od niektórych ekspertów.
ExecutorService service = new ThreadPoolExecutor(10, 10, 1000L,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10, true), new
ThreadPoolExecutor.CallerRunsPolicy());
Zaktualizowano: - Oświadczenie o problemie:
Każdy wątek wykorzystuje unikalny identyfikator od 1 do 1000, a program musi działać przez 60 minut lub dłużej, więc w ciągu tych 60 minut możliwe jest, że wszystkie identyfikatory zostaną ukończone, więc muszę ponownie użyć tych identyfikatorów. Oto poniższy program, który napisałem używając powyższego executora.
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);
}
}
Moje pytania to: - Ten kod ma rację, jeśli chodzi o wydajność, czy nie? Co jeszcze mogę tu zrobić, aby było bardziej dokładne? Każda pomoc zostanie doceniona.