DevShivmohan / Learning-everything

Learning for developer only
0 stars 1 forks source link

Concurrency control and Research #39

Open DevShivmohan opened 7 months ago

DevShivmohan commented 7 months ago

Controlling the request if at a time n no. of request processing in the Queue then avoid the request if greater than n requests.

DevShivmohan commented 4 months ago

Schedule task using Excecutor service


import lombok.*;

import java.util.*;
import java.util.concurrent.*;

public class CodingTest {
    private final static ScheduledExecutorService scheduledExecutorService=Executors.newScheduledThreadPool(1);
    /**
     *  016 -> Octal
     *  0*8^2 + 1*8^1 + 6*8^0 -> decimal
     *  1+16+64   ->   81
     *  https://dummy.restapiexample.com/api/v1/employees
     * @param args
     */
    public static void main (String[] args) throws Throwable{
        Runnable runnable=new CustomScheduler("task1");
        Runnable runnable1=new CustomScheduler("task2");
        Runnable runnable2=new CustomScheduler("task3");
        System.out.println("Scheduling - "+new Date());
        var future= scheduledExecutorService.schedule(runnable,8,TimeUnit.SECONDS); // schedule at currentTime + 8 seconds
        System.out.println("Scheduling - "+new Date());
        var future1= scheduledExecutorService.schedule(runnable1,2,TimeUnit.SECONDS);
//        scheduledExecutorService.shutdown();
        System.out.println("Scheduling - "+new Date());
        var future2= scheduledExecutorService.schedule(runnable2,5,TimeUnit.SECONDS);
//        scheduledExecutorService.shutdown();
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class CustomScheduler implements Runnable{
    private String taskName;
    @Override
    public void run () {
        System.out.println("Scheduled task "+taskName+" at "+new Date());
    }

}