java.nio.channels.AsynchronousChannelGroup Java Examples

The following examples show how to use java.nio.channels.AsynchronousChannelGroup. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TcpManager.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
public synchronized void startServer(SocketAddress addr, Object attachment, AsynchronousChannelGroup group)
{
	stopServer();
	try
	{
		_acceptor = AsynchronousServerSocketChannel.open(group);
		int backlog = onAcceptorCreated(_acceptor, attachment);
		if (backlog >= 0)
		{
			_acceptor.bind(addr, backlog);
			beginAccept();
			return;
		}
	}
	catch (Throwable e)
	{
		doException(null, e);
	}
	stopServer();
}
 
Example #2
Source File: RpcAioAcceptor.java    From hasting with MIT License 6 votes vote down vote up
@Override
public void startService() {
	super.startService();
	try {
		//启动acceptor,开始接受连接
		acceptHandler = new RpcAcceptCompletionHandler();
		acceptHandler.startService();
		channelGroup = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(channelGroupThreads));
		serverChannel = AsynchronousServerSocketChannel.open(channelGroup).bind(new InetSocketAddress(this.getHost(), this.getPort()));
		serverChannel.accept(this, acceptHandler);
		this.startListeners();
		this.fireStartNetListeners();
	} catch (IOException e) {
		throw new RpcException(e);
	}
}
 
Example #3
Source File: TcpManager.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void startClient(SocketAddress addr, Object attachment, AsynchronousChannelGroup group)
{
	AsynchronousSocketChannel channel = null;
	try
	{
		channel = AsynchronousSocketChannel.open(group);
		int recvBufSize = onChannelCreated(channel, attachment);
		if (recvBufSize >= 0)
			channel.connect(addr, new ConnectParam(channel, recvBufSize), _connectHandler);
		else
			channel.close();
	}
	catch (Throwable e)
	{
		doException(null, e);
		closeChannel(channel);
	}
}
 
Example #4
Source File: SslStringClient.java    From smart-socket with Apache License 2.0 6 votes vote down vote up
public void test(AsynchronousChannelGroup asynchronousChannelGroup, BufferPagePool bufferPagePool, AbstractMessageProcessor<String> processor) throws InterruptedException, ExecutionException, IOException {
        AioQuickClient<String> client = new AioQuickClient<>("localhost", 8888, new StringProtocol(), processor);
        client.setBufferPagePool(bufferPagePool);
        client.setWriteBuffer(1024 * 1024, 10);
        AioSession<String> session = client.start(asynchronousChannelGroup);
        WriteBuffer outputStream = session.writeBuffer();

        byte[] data = "smart-socket".getBytes();
        while (true) {
            int num = (int) (Math.random() * 10) + 1;
//            int num = 4;
            outputStream.writeInt(data.length * num);
            while (num-- > 0) {
                outputStream.write(data);
            }

//            Thread.sleep(100);
        }
    }
 
Example #5
Source File: Client.java    From oxygen with Apache License 2.0 6 votes vote down vote up
/**
 * 连接服务端,指定绑定地址
 *
 * @param remote 远程地址
 * @param bind 本机绑定地址
 * @return channelContext
 * @throws IOException io异常时抛出
 */
public ChannelContext connect(InetSocketAddress remote, InetSocketAddress bind)
    throws IOException {
  AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup
      .withThreadPool(groupContext.getGroupExecutor());
  groupContext.setChannelGroup(channelGroup);
  AsynchronousSocketChannel channel = IoUtils.create(channelGroup, bind);
  groupContext.setAioListener(new ComposeAioListener().add(ClientAioListener.INSTANCE)
      .add(groupContext.getAioListener()));

  ChannelContext channelContext = new ChannelContext(groupContext, channel, false);
  channelContext.setServerAddress(remote);
  channel.connect(remote, channelContext, ConnectHandler.INSTANCE);

  BeatProcessor beat = new BeatProcessor(channelContext);
  ThreadUtils.globalTimer()
      .scheduleWithDelay(beat, groupContext.getBeatInterval(), TimeUnit.MILLISECONDS, beat);
  return channelContext;
}
 
Example #6
Source File: StringClient.java    From smart-socket with Apache License 2.0 6 votes vote down vote up
public void test(AsynchronousChannelGroup asynchronousChannelGroup, BufferPagePool bufferPagePool, AbstractMessageProcessor<String> processor) throws InterruptedException, ExecutionException, IOException {
        AioQuickClient<String> client = new AioQuickClient<>("localhost", 8888, new StringProtocol(), processor);
        client.setBufferPagePool(bufferPagePool);
        client.setWriteBuffer(1024 * 1024, 10);
        AioSession<String> session = client.start(asynchronousChannelGroup);
        WriteBuffer outputStream = session.writeBuffer();

        byte[] data = "smart-socket".getBytes();
        while (true) {
            int num = (int) (Math.random() * 10) + 1;
//            int num = 4;
            outputStream.writeInt(data.length * num);
            while (num-- > 0) {
                outputStream.write(data);
            }

//            Thread.sleep(100);
        }
    }
 
Example #7
Source File: AioServerImpl.java    From tephra with MIT License 6 votes vote down vote up
@Override
public void listen(int thread, int port, AioServerListener listener) {
    this.port = port;
    this.listener = listener;
    try {
        channelGroup = AsynchronousChannelGroup.withFixedThreadPool(thread, Executors.defaultThreadFactory());
        serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup);
        serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        serverSocketChannel.bind(new InetSocketAddress(port));
        serverSocketChannel.accept(null, this);

        if (logger.isInfoEnable())
            logger.info("启动AIO监听[{}]服务。", port);
    } catch (IOException e) {
        logger.warn(e, "启动AIO监听[{}]服务时发生异常!", port);
    }
}
 
Example #8
Source File: DbleServer.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private void initAioProcessor(int processorCount) throws IOException {
    for (int i = 0; i < processorCount; i++) {
        asyncChannelGroups[i] = AsynchronousChannelGroup.withFixedThreadPool(processorCount,
                new ThreadFactory() {
                    private int inx = 1;

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread th = new Thread(r);
                        //TODO
                        th.setName(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "AIO" + (inx++));
                        LOGGER.info("created new AIO thread " + th.getName());
                        return th;
                    }
                }
        );
    }
}
 
Example #9
Source File: RpcAioConnector.java    From hasting with MIT License 5 votes vote down vote up
/**
 * 通道异步线程池
 */
private void checkChannelGroup(){
	//检查group
	if(channelGroup==null){
		try {
			channelGroup = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(channelGroupThreads));
		} catch (IOException e) {
			throw new RpcException(e);
		}
	}
}
 
Example #10
Source File: AsyncChannelGroupUtil.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public static AsynchronousChannelGroup register() {
    synchronized (lock) {
        if (usageCount == 0) {
            group = createAsynchronousChannelGroup();
        }
        usageCount++;
        return group;
    }
}
 
Example #11
Source File: AioSocketServer.java    From Tatala-RPC with Apache License 2.0 5 votes vote down vote up
public void setUpHandlers() {
	try {
		AsynchronousChannelGroup asyncChannelGroup = AsynchronousChannelGroup
				.withFixedThreadPool(poolSize,Executors.defaultThreadFactory());
		serverSocketChannel = AsynchronousServerSocketChannel
				.open(asyncChannelGroup).bind(new InetSocketAddress(listenPort));
		serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
		//serverSocketChannel.setOption(StandardSocketOption.TCP_NODELAY, true);
	} catch (IOException e) {
		e.printStackTrace();
	}

	log.info("** " + poolSize + " handler thread has been setup! **");
	log.info("** Socket Server has been startup, listen port is " + listenPort + "! **");
}
 
Example #12
Source File: AsExecutor.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testAttackingTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    Attack task = new Attack();
    executor.execute(task);
    task.waitUntilDone();
    if (!task.failedDueToSecurityException())
        throw new RuntimeException("SecurityException expected");
}
 
Example #13
Source File: AsExecutor.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testSimpleTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    final CountDownLatch latch = new CountDownLatch(1);
    executor.execute(new Runnable() {
        public void run() {
            latch.countDown();
        }
    });
    latch.await();
}
 
Example #14
Source File: AsExecutor.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // create channel groups
    ThreadFactory factory = new PrivilegedThreadFactory();
    AsynchronousChannelGroup group1 = AsynchronousChannelGroup
        .withFixedThreadPool(5, factory);
    AsynchronousChannelGroup group2 = AsynchronousChannelGroup
        .withCachedThreadPool(Executors.newCachedThreadPool(factory), 0);
    AsynchronousChannelGroup group3 = AsynchronousChannelGroup
        .withThreadPool(Executors.newFixedThreadPool(10, factory));

    try {
        // execute simple tasks
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // install security manager and test again
        System.setSecurityManager( new SecurityManager() );
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // attempt to execute tasks that run with only frames from boot
        // class loader on the stack.
        testAttackingTask(group1);
        testAttackingTask(group2);
        testAttackingTask(group3);
    } finally {
        group1.shutdown();
        group2.shutdown();
        group3.shutdown();
    }
}
 
Example #15
Source File: AsExecutor.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testAttackingTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    Attack task = new Attack();
    executor.execute(task);
    task.waitUntilDone();
    if (!task.failedDueToSecurityException())
        throw new RuntimeException("SecurityException expected");
}
 
Example #16
Source File: AioSocketServer.java    From Tatala-RPC with Apache License 2.0 5 votes vote down vote up
public void setUpHandlers() {
	try {
		AsynchronousChannelGroup asyncChannelGroup = AsynchronousChannelGroup.withFixedThreadPool(poolSize, Executors.defaultThreadFactory());
		serverSocketChannel = AsynchronousServerSocketChannel.open(asyncChannelGroup).bind(new InetSocketAddress(listenPort));
		serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
		
		log.info("** " + poolSize + " handler thread has been setup! **");
		log.info("** Socket Server has been startup, listen port is " + listenPort + "! **");
	} catch (IOException e) {
		log.error("setUpHandlers error: ", e);
	}
}
 
Example #17
Source File: AIOAcceptor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public AIOAcceptor(String name, String ip, int port,
		FrontendConnectionFactory factory, AsynchronousChannelGroup group)
		throws IOException {
	this.name = name;
	this.port = port;
	this.factory = factory;
	serverChannel = AsynchronousServerSocketChannel.open(group);
	/** 设置TCP属性 */
	serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
	serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 1024 * 16 * 2);
	// backlog=100
	serverChannel.bind(new InetSocketAddress(ip, port), 100);
}
 
Example #18
Source File: AsExecutor.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static void testSimpleTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    final CountDownLatch latch = new CountDownLatch(1);
    executor.execute(new Runnable() {
        public void run() {
            latch.countDown();
        }
    });
    latch.await();
}
 
Example #19
Source File: AsExecutor.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // create channel groups
    ThreadFactory factory = new PrivilegedThreadFactory();
    AsynchronousChannelGroup group1 = AsynchronousChannelGroup
        .withFixedThreadPool(5, factory);
    AsynchronousChannelGroup group2 = AsynchronousChannelGroup
        .withCachedThreadPool(Executors.newCachedThreadPool(factory), 0);
    AsynchronousChannelGroup group3 = AsynchronousChannelGroup
        .withThreadPool(Executors.newFixedThreadPool(10, factory));

    try {
        // execute simple tasks
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // install security manager and test again
        System.setSecurityManager( new SecurityManager() );
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // attempt to execute tasks that run with only frames from boot
        // class loader on the stack.
        testAttackingTask(group1);
        testAttackingTask(group2);
        testAttackingTask(group3);
    } finally {
        group1.shutdown();
        group2.shutdown();
        group3.shutdown();
    }
}
 
Example #20
Source File: AsExecutor.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static void testAttackingTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    Attack task = new Attack();
    executor.execute(task);
    task.waitUntilDone();
    if (!task.failedDueToSecurityException())
        throw new RuntimeException("SecurityException expected");
}
 
Example #21
Source File: MycatServer.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * get next AsynchronousChannel ,first is exclude if multi
 * AsynchronousChannelGroups
 *
 * @return
 */
public AsynchronousChannelGroup getNextAsyncChannelGroup() {
    if (asyncChannelGroups.length == 1) {
        return asyncChannelGroups[0];
    } else {
        int index = (++channelIndex) % asyncChannelGroups.length;
        if (index == 0) {
            ++channelIndex;
            return asyncChannelGroups[1];
        } else {
            return asyncChannelGroups[index];
        }

    }
}
 
Example #22
Source File: AsExecutor.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // create channel groups
    ThreadFactory factory = new PrivilegedThreadFactory();
    AsynchronousChannelGroup group1 = AsynchronousChannelGroup
        .withFixedThreadPool(5, factory);
    AsynchronousChannelGroup group2 = AsynchronousChannelGroup
        .withCachedThreadPool(Executors.newCachedThreadPool(factory), 0);
    AsynchronousChannelGroup group3 = AsynchronousChannelGroup
        .withThreadPool(Executors.newFixedThreadPool(10, factory));

    try {
        // execute simple tasks
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // install security manager and test again
        System.setSecurityManager( new SecurityManager() );
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // attempt to execute tasks that run with only frames from boot
        // class loader on the stack.
        testAttackingTask(group1);
        testAttackingTask(group2);
        testAttackingTask(group3);
    } finally {
        group1.shutdown();
        group2.shutdown();
        group3.shutdown();
    }
}
 
Example #23
Source File: AsExecutor.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testSimpleTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    final CountDownLatch latch = new CountDownLatch(1);
    executor.execute(new Runnable() {
        public void run() {
            latch.countDown();
        }
    });
    latch.await();
}
 
Example #24
Source File: AsExecutor.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static void testSimpleTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    final CountDownLatch latch = new CountDownLatch(1);
    executor.execute(new Runnable() {
        public void run() {
            latch.countDown();
        }
    });
    latch.await();
}
 
Example #25
Source File: AsExecutor.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // create channel groups
    ThreadFactory factory = new PrivilegedThreadFactory();
    AsynchronousChannelGroup group1 = AsynchronousChannelGroup
        .withFixedThreadPool(5, factory);
    AsynchronousChannelGroup group2 = AsynchronousChannelGroup
        .withCachedThreadPool(Executors.newCachedThreadPool(factory), 0);
    AsynchronousChannelGroup group3 = AsynchronousChannelGroup
        .withThreadPool(Executors.newFixedThreadPool(10, factory));

    try {
        // execute simple tasks
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // install security manager and test again
        System.setSecurityManager( new SecurityManager() );
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // attempt to execute tasks that run with only frames from boot
        // class loader on the stack.
        testAttackingTask(group1);
        testAttackingTask(group2);
        testAttackingTask(group3);
    } finally {
        group1.shutdown();
        group2.shutdown();
        group3.shutdown();
    }
}
 
Example #26
Source File: AsExecutor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void testAttackingTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    Attack task = new Attack();
    executor.execute(task);
    task.waitUntilDone();
    if (!task.failedDueToSecurityException())
        throw new RuntimeException("SecurityException expected");
}
 
Example #27
Source File: AsExecutor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void testSimpleTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    final CountDownLatch latch = new CountDownLatch(1);
    executor.execute(new Runnable() {
        public void run() {
            latch.countDown();
        }
    });
    latch.await();
}
 
Example #28
Source File: AsExecutor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // create channel groups
    ThreadFactory factory = new PrivilegedThreadFactory();
    AsynchronousChannelGroup group1 = AsynchronousChannelGroup
        .withFixedThreadPool(5, factory);
    AsynchronousChannelGroup group2 = AsynchronousChannelGroup
        .withCachedThreadPool(Executors.newCachedThreadPool(factory), 0);
    AsynchronousChannelGroup group3 = AsynchronousChannelGroup
        .withThreadPool(Executors.newFixedThreadPool(10, factory));

    try {
        // execute simple tasks
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // install security manager and test again
        System.setSecurityManager( new SecurityManager() );
        testSimpleTask(group1);
        testSimpleTask(group2);
        testSimpleTask(group3);

        // attempt to execute tasks that run with only frames from boot
        // class loader on the stack.
        testAttackingTask(group1);
        testAttackingTask(group2);
        testAttackingTask(group3);
    } finally {
        group1.shutdown();
        group2.shutdown();
        group3.shutdown();
    }
}
 
Example #29
Source File: AsExecutor.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testAttackingTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    Attack task = new Attack();
    executor.execute(task);
    task.waitUntilDone();
    if (!task.failedDueToSecurityException())
        throw new RuntimeException("SecurityException expected");
}
 
Example #30
Source File: DbleServer.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
/**
 * get next AsynchronousChannel ,first is exclude if multi
 * AsynchronousChannelGroups
 *
 * @return AsynchronousChannelGroup
 */
public AsynchronousChannelGroup getNextAsyncChannelGroup() {
    if (asyncChannelGroups.length == 1) {
        return asyncChannelGroups[0];
    } else {
        int index = (channelIndex.incrementAndGet()) % asyncChannelGroups.length;
        if (index == 0) {
            channelIndex.incrementAndGet();
            return asyncChannelGroups[1];
        } else {
            return asyncChannelGroups[index];
        }

    }
}