Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
How use a single instance of a class for all request RestController

I have class Named as PriorityJobScheduler and in RestControll i want create its object only once to for all the request for that I am instanciating this class in @PostConstruct method but for each new request i am getting a new object.

I want know how can i instanciate this class only once and use its object for all requests.

public class PriorityJobScheduler {
 Logger log = LoggerFactory.getLogger(PriorityJobScheduler.class);

 private ExecutorService priorityJobPoolExecutor;
 private ExecutorService priorityJobScheduler = 
                Executors.newSingleThreadExecutor();
 private PriorityBlockingQueue<DowloadProccess> priorityQueue;

 public PriorityJobScheduler(Integer poolSize, Integer queueSize) {
    Comparator<DowloadProccess> priorityComparator = Comparator.comparingInt(DowloadProccess::getJobPriority).reversed();
    
    priorityJobPoolExecutor = Executors.newFixedThreadPool(poolSize);
    priorityQueue = new PriorityBlockingQueue<DowloadProccess>(queueSize, priorityComparator);
    priorityJobScheduler.execute(() -> {
        while (true) {
            try {
                log.debug(priorityQueue.take().toString());
                priorityJobPoolExecutor.execute(priorityQueue.take());
            } catch (InterruptedException e) {
                break;
            }
        }
    });
}


   public void scheduleJob(DowloadProccess job) {   
       priorityQueue.add(job);   
       log.debug("Jobs in queu :: " +  priorityQueue.size());   
   }   

}

My controller

@RestController
   public class ZcrController {
    private static int POOL_SIZE = 1;
    private static int QUEUE_SIZE = 100;
    PriorityJobScheduler pjs;
    
    
    @PostConstruct
    public void init() {
         pjs = new PriorityJobScheduler(POOL_SIZE, QUEUE_SIZE);
    }
    
    @GetMapping("/zcr/run")
    public List<Map<String,Object>>  exicuteCRTask(@RequestParam(required = false) String agentId,@RequestParam(required = false) String callCenterId,
            @RequestParam(required = false) String clientId,@RequestParam(required = false) String skillId,
            @RequestParam(required = false) String interval,@RequestParam("callRecordingId") String callRecordingId,@RequestParam(required = false) String type, @RequestParam(required = false) String customReport,@RequestParam(required = false) boolean ivrAcd,
            @RequestParam(required = false) String endDate, @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime) {
        ITxn txn = new TxnToken();
        List<Map<String,Object>> listCDRDetail = dao.getIvrRecords(txn, params,dbParam,type);
        log.debug("CDR bean size::" +listCDRDetail.size());
      
        // Here I am passing of instance of that class.
        // And on each new request i am getting a new instance pjs.
        taskExecutor.runZcrJob(pjs, dbParam, listCDRDetail, type, txn);
        return listCDRDetail;
        
    }   
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can create the bean in the Spring container

@Configuration
class JobSchedulerConfig {
    private static int POOL_SIZE = 1;
    private static int QUEUE_SIZE = 100;

    @Bean
    public PriorityJobScheduler createJobScheduler() {
         return new PriorityJobScheduler(POOL_SIZE, QUEUE_SIZE);
    }
}

And then Inject this bean in the Rest Controller.

@RestController
public class ZcrController {

   private final PriorityJobScheduler priorityJobScheduler;

   @Autowired // kept it for readability
   public ZcrController(PriorityJobScheduler priorityJobScheduler) {
      this.priorityJobScheduler = priorityJobScheduler;
   }

   ...
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda