K
K
KSenobait2014-01-18 15:38:49
Java
KSenobait, 2014-01-18 15:38:49

Should I use a separate thread for each task in Java?

There is a program that must periodically perform certain actions (check the database for new records, check for files, etc.).
The question is, is it worth creating a separate thread to perform each of the tasks, given that most of the time these threads will sleep, or just get by with a regular timer?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2014-01-18
@KSenobait

If there are any events to which the application must immediately respond, then of course the flows. If the main task of the application is these checks, then the timer is enough.

F
FanKiLL, 2014-01-18
@FanKiLL

I would do something like this if you need to check once every N time.

public class Main {
  private static int period = 60; //Default period
  private static final TimeUnit PERIOD_TIME_UNIT = TimeUnit.MINUTES;

  public static void main(String[] args) {
    
  ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

  System.out.println(String.format("Worker work period %d %s", period, PERIOD_TIME_UNIT));
  scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
      
    @Override
    public void run() {
      //код который должен запускатся по таймеру
    }
  }, 0, period, TimeUnit.MINUTES);				
  }
}

Well, if this is part of the application logic, then I would use a simple ThreadPoolExecutorone. For this, I have a class with callbacks written like the Android AsyncTaskonPostExecuteonPreExecutedoInBackground , to which you give Runnableit to execute them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question