I need to create two threads , one invoking a scheduler executor service and the other which runs in an infinite loop to fetch and process files.
I use the following code:
ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(new Runnable() {
public void run()
{
obj.checkFileExist();
obj.enqueue();
}
}, 0, 1, TimeUnit.MINUTES);
And in an infinite loop I process files one by one:
public class processModel extends Thread{
public static void getQueueSize(int size)
{
System.out.println("getting queue size");
}
public void dequeue()
{
// dequeue the queue
System.out.println("dequeue");
}
public void processFile()
{
// process the file
System.out.println("process file");
}
public static void main(String[] args) {
final boolean flag = true;
final int size = 9;
final processModel obj = new processModel();
Thread t1 = new Thread(){
public void run()
{
while(flag)
{
obj.dequeue();
obj.processFile();
getQueueSize(size);
}
}
};
t1.start();
}
}
How can I achieve both concurrently?
- Thread 1 – check if file exists in a folder. if yes enqueue it else sleep for a min.. – scheduler can perform this
- Thread 2 – if queue is non empty , process one by one. else sleep for a minute
How can I run these 2 threads concurrently. It would help me a lot if you show up some code.
Using two threads doesn’t make any sense. The only time both thread will run at once is when the enqueuer is picking up files faster than the dequeuer can process them. You solution would be simpler and more robust if you has a single repeating task which will ensure you never have one thread critically always ahead of the other ( and the code is much simpler)