In the below program,
//Producer - IO bound
public class FileCrawler implements Runnable{
private final BlockingQueue<File> fileQueue;
private final File root;
....
public void run(){
try{
crawl(root); // IO bound
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
private void crawl(File root) throws InterruptedException{
File[] entries = root.listFiles(fileFilter);
...
for(File entry: entries){
fileQueue.put(entry);
}
}
}
//Consumer - CPU bound
public class Indexer implements Runnable{
private final BlockingQueue<File> queue;
....
public void run(){
try{
while(true){
indexFile(queue.take()); // CPU bound
}
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
}
FileCrawler
is IO bound runnable task that gets launched on multiple threads which perform crawl(root)
IO functionality.
Java thread is internally mapped to native thread(equivalent to pthread_create()
). Each pthread is mapped to a different thread in the kernel, and the kernel is responsible for scheduling the threads.
So, each java thread is visible to OS. It runs on specific cpu core.
Assume java process is running on OS that follows 1:1 threading model.
A java thread performing IO on a cpu core,
Does producer thread waiting on IO triggers kernel to context switch out the java process and put the java process into a waiting state until the IO is ready to be processed? Not getting chance for other threads(CPU bound) of java process to consume CPU time slice.