Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda