Example of AsynchronousChannelGroup in Java NIO Channels

By Arvind Rai, November 27, 2013
AsynchronousChannelGroup has been introduced in JDK 7. AsynchronousChannelGroup belongs to the package java.nio.channels. AsynchronousChannelGroup performs resource sharing in the group of asynchronous channels. AsynchronousChannelGroup instance is created using its static method withFixedThreadPool and withCachedThreadPool. AsynchronousChannelGroup provides the method to shut down the complete thread groups. In our example we have taken a simple example to show demo of AsynchronousChannelGroup.

AsynchronousChannelGroupTest.java
package com.concretepage.nio.channels;
import java.io.IOException;
import java.nio.channels.AsynchronousChannelGroup;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class AsynchronousChannelGroupTest {
	public static void main(String[] args) throws IOException, InterruptedException {
		Runnable r= new AsynchronousChannelGroupTest(). new SampleThread();
		ExecutorService service = Executors.newCachedThreadPool();
		service.execute(r);
		AsynchronousChannelGroup acg = AsynchronousChannelGroup.withCachedThreadPool(service, 2);
		
		System.out.println(acg.isShutdown());
		acg.awaitTermination(2,TimeUnit.SECONDS);
		acg.shutdownNow();
	}
	class SampleThread implements Runnable {
        @Override
        public void run() {
            for (int cnt =0; cnt<5 ; cnt++) {
                System.out.println("run:" + cnt);
            }
        }
    }
}
 
In the above example, we have a Runnable thread and a cached thread pool. Runnable thread is being executed by ExecutorService and then this ExecutorService has been passed to AsynchronousChannelGroup. Thread will run and once finished, awaitTermination method will terminates the thread two after seconds and finally shutdown.

Output
run:0
run:1
run:2
run:3
run:4
false
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us