private static AsynchronousChannelGroup createAsynchronousChannelGroup() { // Need to do this with the right thread context class loader else the // first web app to call this will trigger a leak ClassLoader original = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(AsyncIOThreadFactory.class.getClassLoader()); // These are the same settings as the default // AsynchronousChannelGroup int initialSize = Runtime.getRuntime().availableProcessors(); ExecutorService executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, Long.MAX_VALUE, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new AsyncIOThreadFactory()); try { return AsynchronousChannelGroup.withCachedThreadPool(executorService, initialSize); } catch (IOException e) { // No good reason for this to happen. throw new IllegalStateException(sm.getString("asyncChannelGroup.createFail")); } } finally { Thread.currentThread().setContextClassLoader(original); } }
@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); } }
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(); }
@SuppressWarnings("resource") 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); } }
@Override public void run() { try { final int workerThreads = Math.max(4, 2 * Runtime.getRuntime().availableProcessors()); channelGroup = AsynchronousChannelGroup.withFixedThreadPool( workerThreads, Executors.defaultThreadFactory()); serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup); serverSocketChannel.bind(new InetSocketAddress(port)); serverSocketChannel.accept(null, new AcceptCompletionHandler(serverSocketChannel)); channelGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); } catch(IOException | InterruptedException ex) { Log.get().log(Level.SEVERE, ex.getLocalizedMessage(), ex); } }
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); }
/** * 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]; } } }
public static AsynchronousChannelGroup register() { synchronized (lock) { if (usageCount == 0) { group = createAsynchronousChannelGroup(); } usageCount++; return group; } }
private static AsynchronousChannelGroup createAsynchronousChannelGroup() { // Need to do this with the right thread context class loader else the // first web app to call this will trigger a leak ClassLoader original = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( AsyncIOThreadFactory.class.getClassLoader()); // These are the same settings as the default // AsynchronousChannelGroup int initialSize = Runtime.getRuntime().availableProcessors(); ExecutorService executorService = new ThreadPoolExecutor( 0, Integer.MAX_VALUE, Long.MAX_VALUE, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new AsyncIOThreadFactory()); try { return AsynchronousChannelGroup.withCachedThreadPool( executorService, initialSize); } catch (IOException e) { // No good reason for this to happen. throw new IllegalStateException(sm.getString("asyncChannelGroup.createFail")); } } finally { Thread.currentThread().setContextClassLoader(original); } }
private AsynchronousChannelGroup getAsynchronousChannelGroup() { // Use AsyncChannelGroupUtil to share a common group amongst all // WebSocket clients AsynchronousChannelGroup result = asynchronousChannelGroup; if (result == null) { synchronized (asynchronousChannelGroupLock) { if (asynchronousChannelGroup == null) { asynchronousChannelGroup = AsyncChannelGroupUtil.register(); } result = asynchronousChannelGroup; } } return result; }
private DefaultThreadPool(final int numberOfThreads, final ThreadPoolId id) { this.id = id; if (ThreadPoolId.WorkStealing == id) { this.executorService = new ForkJoinPool( numberOfThreads /* parallelism level */, ForkJoinPool.defaultForkJoinWorkerThreadFactory, EhSupport.getUncaughtHandler() /* uncaught exception handler */, true /* asyncMode */ ); } else { this.executorService = Executors.newFixedThreadPool( numberOfThreads, (runnable) -> defaultFactory.newThread(() -> EhSupport.fatalOnException(() -> { Thread.currentThread().setUncaughtExceptionHandler(EhSupport.getUncaughtHandler()); runnable.run(); })) ); } if (ThreadPoolId.NonBlocking == this.id) { try { this.ioService = EhSupport.propagateFn( () -> AsynchronousChannelGroup.withThreadPool(this.executorService) ); } catch (final Throwable throwable) { this.executorService.shutdownNow(); throw throwable; } } else { this.ioService = null; } }
@Override public AsynchronousChannelGroup ioService() { EhSupport.ensureOrFatal( null != this.ioService, "I/O service requested for thread pool which does not support it" ); return this.ioService; }
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(); } }
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(); }
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"); }
/** * 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]; } } }
/** * init the aioServer * * @param port * @param channelWorkers * @throws IOException */ public AioServer(int port, ExecutorService channelWorkers , AioDataDealerFactory aioDataDealerFactory) throws IOException { this.aioDataDealerFactory = aioDataDealerFactory; channelGroup = AsynchronousChannelGroup.withThreadPool(channelWorkers); this.port = port; listener = createListener(channelGroup); acceptHandler = new AcceptHandler(); }
private AsynchronousServerSocketChannel createListener(AsynchronousChannelGroup channelGroup) throws IOException { final AsynchronousServerSocketChannel listener = openChannel(channelGroup); listener.setOption(StandardSocketOptions.SO_REUSEADDR, true); listener.setOption(StandardSocketOptions.SO_RCVBUF, 16 * 1024); listener.bind(new InetSocketAddress(port), 0); return listener; }
public void start(String serverIp, int serverPort) throws IOException { this.serverNode = new Node(serverIp, serverPort); ExecutorService groupExecutor = serverGroupContext.getGroupExecutor(); AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withThreadPool(groupExecutor); serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup); serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 64 * 1024); InetSocketAddress listenAddress = null; if (StringUtils.isBlank(serverIp)) { listenAddress = new InetSocketAddress(serverPort); } else { listenAddress = new InetSocketAddress(serverIp, serverPort); } serverSocketChannel.bind(listenAddress, 0); AcceptCompletionHandler<SessionContext, P, R> acceptCompletionHandler = serverGroupContext.getAcceptCompletionHandler(); serverSocketChannel.accept(this, acceptCompletionHandler); System.out.println("start server on " + this.serverNode); }
protected AsynchronousSocketChannel openSocketChannel( AsynchronousChannelGroup asynchronousChannelGroup) throws IOException { AsynchronousSocketChannel channel = AsynchronousSocketChannel.open(asynchronousChannelGroup); channel.setOption(StandardSocketOptions.TCP_NODELAY, true); channel.setOption(StandardSocketOptions.SO_REUSEADDR, false); channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); return channel; }
public static AsynchronousChannelGroup newChannelGroup() throws IOException { final AtomicInteger counter = new AtomicInteger(); ExecutorService transportExec = Executors.newFixedThreadPool(16, (Runnable r) -> { Thread t = new Thread(r); t.setDaemon(true); t.setName("Transport-Thread-" + counter.incrementAndGet()); return t; }); return AsynchronousChannelGroup.withCachedThreadPool(transportExec, 1); }
@Setup public void init() throws IOException { System.out.println("Setup"); monitor.set(0); if (executorService == null) { executorService = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).build()); } if (asynChanGroupFibers == null) { asynChanGroupFibers = AsynchronousChannelGroup.withThreadPool((ExecutorService) DefaultFiberScheduler.getInstance().getExecutor()); } if (asynChanGroupFJP == null) { asynChanGroupFJP = AsynchronousChannelGroup.withThreadPool(ForkJoinPool.commonPool()); } }