有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用不同的唯一id提高每个线程的java性能

问题陈述是:-

每个线程使用1到1000之间的唯一ID,程序必须运行60分钟或更长时间,因此在这60分钟内,所有ID都可能完成,因此我需要再次重用这些ID,

我知道几种方法,其中一种方法是我在StackOverflow的帮助下写的,但当我试着运行这个程序时,我发现,运行几分钟后,这个程序变得非常慢,在控制台上打印ID需要很多时间。而且我有时也会因为记忆错误而放弃。有没有更好的办法来解决这种问题

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);
    }

    private void someMethod(Integer id) {
        System.out.println("Task: " +id);
    }
}

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
        // create thread pool with given size
    ExecutorService service = new ThreadPoolExecutor(size, size, 500L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), 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); 
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我已经在前面的问题中解释过,您的代码向执行器提交了数百万个任务,因为它在60分钟内以循环方式提交任务,而不需要等待

    目前还不清楚你的最终目标是什么,但事实上,你正在完成一系列任务,直到你没有任何可用的内存。因为你没有解释你计划的目标,所以很难给你任何解决方案

    但是,您可以做的第一件事是限制执行者任务队列的大小。这将迫使主线程在每次队列满时阻塞