'How to make a thread limit in java?

I have a node program that starts a thread everytime a job packet is sent to it with seconds to complete from the load balancer. The thread sends a packet back to load balancer once the thread is complete (it waits to send based on the seconds given in the packet). The node has a maximum capacity given in which it can process jobs at the same time. Currently it completes the job with no limit and i would need to have a limit to the amount of threads that can work at the same time based of the nodes capacity

public void run() {
    try {
        //Puts thread to sleep based from jobTime
        TimeUnit.SECONDS.sleep(jobTime);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    System.out.println("job " + jobID + " completed and sent to loadbalancer! " + this);
    Node.getMessageSender().getJobList().remove(this);

    //String created to send finished job packet
    String finData = "FINISH," + jobID + "," + Node.getMessageSender().getPort();
    DatagramPacket finPacket = new DatagramPacket(finData.getBytes(), finData.length(),
            Node.getMessageSender().getAddress(), Node.getMessageSender().getPort());
    try {
        //Sends message to loadbalancer
        Node.getMessageSender().getSocket().send(finPacket);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Edit: The node must accept all the other incoming job packets and queue them until the node is no longer at maximum capacity



Solution 1:[1]

You're going to have to think about what it means if a job is handed to your node when the node is at max cap. Should it be rejected? Should it be accepted and queued up? At any rate, the answer most likely lies in the java.util.concurrent package, for example, ThreadPoolExecutor.

If you must roll that yourself (not sure why, but let's say), you'd have to program it. Java library classes are open source; you can look at the impl of ThreadPoolExecutor for inspiration.

Generally a central thread operates as distribution and management system. Have an AtomicInteger or CountdownLatch that each spawning thread increments, and, in a try/finally block, decrements upon completion. Deny incoming requests (or block, the latch could be useful there, if that's what you want to do). If instead you'd want to toss the job in a queue of tasks to be completed, then you really should be using TPE.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rzwitserloot