Home > Back-end >  Is there anyway to keep threads alive and assign different tasks to thread when needed - Java
Is there anyway to keep threads alive and assign different tasks to thread when needed - Java

Time:11-25

I'm trying to create 10 threads for our Java application and keep them alive all the time. These 10 threads should be alive all the time and run the tasks I assign to them. The tasks I'm trying to assign them are the file downloads, report downloads, and PDF downloads.

I tried to let keep them alive by asking them to sleep all the time and interrupt them when assigning new tasks to them. However, those file generation are based on different parameters in our system so that I cannot define my file generating logic in InterruptedException exception catch block. I'm curiouse whether there's a way to interrupt the threads and assign them different tasks(functions) in classes that don't extends thread or implement runable interface?

I created 10 threads sleeping all the time, and add them to a public static arraylist.

for (int i = 0; i < NUM_THREADS_DOWNLOAD; i   ) {
    Thread tempT = new Thread() {
        public void run(){
            Thread.currentThread().setName(BriString.value(WebServer.getThreadIndex()));
            while (true) {
                try {
                    sleep(300);
                } catch (InterruptedException e) {
                    //DYNAMIC LOGIC OF FILE/REPORT/PDF GENERATION
                }
            }
        }
    };
    tempT.start();
    DOWNLOAD_THREAD_POOL.add(tempT);
}

Below is the code that I tried to access the threads alive and wants to add the logic there.

for (int i = 0; i < WebServer.DOWNLOAD_THREAD_POOL.size(); i  ) {
    Thread tempT = WebServer.DOWNLOAD_THREAD_POOL.get(i);
    String currentName = tempT.getName().replaceAll("\\D ","");
    if (tempT.isAlive()) {
        tempT.interrupt();
        // TRYING TO ADD THE FORM/FILE/PDF GENERATION LOGIC HERE
        // ONCE TASK AS FINISHED BY 1 THREAD, WE EXIST FINDING THE THREAD AVAILABLE
        break;
    }
}

Thank you in advance.

CodePudding user response:

In modern Java we rarely need to address Thread class directly. Instead we use the Executors framework to mange threads on our behalf.

I'm trying to create 10 threads for our Java application

If you are confident that 10 threads is appropriate for your work load on your deployment computers, then simple create an executor service backed by ten threads.

ExecuterService executorService = Executors.newFixedThreadPool( 10 ) ;

By the way, if Project Loom succeeds, even this judgement on your part will likely go away. The new virtual threads (fibers) will be so “cheap” that we can have thousands, even millions, of threads running at a time. And these virtual threads will all be new and fresh, with no need to recycle them in a pool. Experimental builds with Project Loom technology are available now, based on early-access Java 18.

ExecuterService executorService = Executors.newVirtualThreadPerTaskExecutor() ;

keep them alive all the time

No need for that. Let the executor service manage its backing thread pool.

run the tasks I assign to them.

Define your task as either a Runnable or a Callable.

Runnable weeklyReportTask = () -> WeeklyReport :: generate ;

Submit an instance of your task to the executor service.

executorService.submit( weeklyReportTask ) ;

The tasks I'm trying to assign them are the file downloads, report downloads, and PDF downloads.

Just keep on submitting tasks. The executor service takes care of juggling task assignments to the threads in its backing thread pool.

executorService.submit( fileDownloadTask ) ;
executorService.submit( weeklyReportTask ) ;
executorService.submit( pdfDownloadTask ) ;

However, those file generation are based on different parameters in our system so that I cannot define my file generating logic in InterruptedException exception catch block. I'm curiouse whether there's a way to interrupt the threads and assign them different tasks(functions) in classes that don't extends thread or implement runable interface?

Define your task as an instance of a class of your own design that implements Runnable and carries a run method. Put a constructor on your task class that takes arguments for those different parameters that affect your file generating logic. Pass the arguments when instantiating your task object. Then submit the task instance to your executor service.

Your Runnable implementation then contains all the information it needs to do its job. No need to interrupt threads; no need to even know about any threads specifically.

All of this has been addressed many times on Stack Overflow. Search to learn more.

  • Related