终结全网!手写Netty面试题答案,2024年最新java程序员面试笔试宝典郭晶晶

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip1024b (备注Java)
img

正文

while (iterable.hasNext()) {

// 拿到该 key

SelectionKey key = iterable.next();

// 拿到后就移除它,否则后面遍历还会重复拿到它

iterable.remove();

// 连接事件

if (key.isAcceptable()) {

ServerSocketChannel ssc = (ServerSocketChannel) key.channel();

// 接受客户端的连接,一个 SocketChannel 代表一个TCP连接

SocketChannel socketChannel = ssc.accept();

// 把SocketChannel设置为非阻塞模式

socketChannel.configureBlocking(false);

System.out.println("服务器接受了一个新的连接 " + socketChannel.getRemoteAddress());

}

}

}

}

}

package io.netty.example.helloworld;

import io.netty.channel.EventLoopGroup;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.channels.spi.SelectorProvider;

import java.util.Arrays;

import java.util.Iterator;

import java.util.Set;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.LinkedBlockingQueue;

import java.util.concurrent.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

/**

  • @author JavaEdge

  • @date 2021/5/17

*/

public class NioServer {

public static void main(String[] args) throws Exception {

//创建一个ServerSocket

ServerSocketChannel serverChannel = ServerSocketChannel.open();

serverChannel.bind(new InetSocketAddress(8089));

//设置为非阻塞模式

serverChannel.configureBlocking(false);

// 创建一个事件查询器

Selector selector = SelectorProvider.provider().openSelector();

// 把 ServerSocketChannel 注册到事件查询器上,并且感兴趣 OP_ACCEPT 事件

serverChannel.register(selector, SelectionKey.OP_ACCEPT);

//

// //创建一组事件查询器

// EventLoopGroup eventLoopGroup = new EventLoopGroup();

while (true) {

// 阻塞方法,等待系统有I/O事件发生

int eventNum = selector.select();

System.out.println(“系统发生IO事件 数量->” + eventNum);

Set keySet = selector.selectedKeys();

Iterator iterable = keySet.iterator();

while (iterable.hasNext()) {

// 拿到该 key

SelectionKey key = iterable.next();

// 拿到后就移除它,否则后面遍历还会重复拿到它

iterable.remove();

// 连接事件

if (key.isAcceptable()) {

// 因为只有 ServerSocketChannel 有接收事件,所以可直接强转

ServerSocketChannel ssc = (ServerSocketChannel) key.channel();

// 接受客户端的连接,一个 SocketChannel 代表一个TCP连接

// 事件如果发生了,就肯定有新的连接

SocketChannel socketChannel = ssc.accept();

// 把SocketChannel设置为非阻塞模式

socketChannel.configureBlocking(false);

System.out.println("服务器接受了一个新的连接 " + socketChannel.getRemoteAddress());

// 把SocketChannel注册到Selector,并关注OP_READ事件

socketChannel.register(selector, SelectionKey.OP_READ);

// eventLoopGroup.register(socketChannel, SelectionKey.OP_READ);

}

// 可读事件

if (key.isReadable()) {

SocketChannel socketChannel = (SocketChannel) key.channel();

ByteBuffer buffer = ByteBuffer.allocate(1024);

try {

int readNum = socketChannel.read(buffer);

if (readNum == -1) {

System.out.println(“读取结束,关闭 socket”);

key.channel();

socketChannel.close();

break;

}

// 将Buffer从写模式切到读模式

buffer.flip();

byte[] bytes = new byte[readNum];

buffer.get(bytes, 0, readNum);

System.out.println(new String(bytes));

/* byte[] response = “client hello”.getBytes();

// 清理了才可以重新使用

buffer.clear();

buffer.put(response);

buffer.flip();

// 该方法非阻塞的,如果此时无法写入也不会阻塞在此,而是直接返回 0 了

socketChannel.write(buffer);

*/

// 在 key 上附加一个对象

key.attach(“hello client”.getBytes());

// 把 key 关注的事件切换为写

key.interestOps(SelectionKey.OP_WRITE);

} catch (IOException e) {

System.out.println(“读取时发生异常,关闭 socket”);

// 取消 key

key.channel();

}

}

if (key.isWritable()) {

SocketChannel socketChannel = (SocketChannel) key.channel();

// 可写时再将那个对象拿出来

byte[] bytes = (byte[]) key.attachment();

key.attach(null);

System.out.println(“可写事件发生 写入消息” + Arrays.toString(bytes));

if (bytes != null) {

socketChannel.write(ByteBuffer.wrap(bytes));

}

// 写完后,就不需要写了,就切换为读事件 如果不写该行代码就会死循环

// key.interestOps(SelectionKey.OP_READ);

}

}

}

}

}

2 接收请求单独处理

=========================================================================

  • 架构图

2.1 死锁案例


package io.netty.example.helloworld;

import java.net.InetSocketAddress;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.channels.spi.SelectorProvider;

import java.util.Iterator;

import java.util.Set;

/**

  • @author JavaEdge

  • @date 2021/5/17

*/

public class NioServer {

public static void main(String[] args) throws Exception {

// 创建一个ServerSocket

ServerSocketChannel serverChannel = ServerSocketChannel.open();

serverChannel.bind(new InetSocketAddress(8089));

// 设置为非阻塞模式

serverChannel.configureBlocking(false);

// 创建一个事件查询器

Selector selector = SelectorProvider.provider().openSelector();

// 把 ServerSocketChannel 注册到事件查询器上,并且感兴趣 OP_ACCEPT 事件

serverChannel.register(selector, SelectionKey.OP_ACCEPT);

EventLoop eventLoop = new EventLoop();

while (true) {

// 阻塞方法,等待系统有I/O事件发生

int eventNum = selector.select();

System.out.println(“系统发生IO事件 数量->” + eventNum);

Set selectedKeys = selector.selectedKeys();

Iterator keyIterator = selectedKeys.iterator();

while (keyIterator.hasNext()) {

// 拿到该 key

SelectionKey key = keyIterator.next();

// 拿到后就移除它,否则后面遍历还会重复拿到它

keyIterator.remove();

// 只需处理【连接事件】 a connection was accepted by a ServerSocketChannel.

if (key.isAcceptable()) {

// 因为只有 ServerSocketChannel 有接收事件,所以可直接强转

ServerSocketChannel ssc = (ServerSocketChannel) key.channel();

// 接受客户端的连接,一个 SocketChannel 代表一个TCP连接

// 事件如果发生了,就肯定有新的连接

SocketChannel socketChannel = ssc.accept();

// 把SocketChannel设置为非阻塞模式

socketChannel.configureBlocking(false);

System.out.println("服务器接受了一个新的连接 " + socketChannel.getRemoteAddress());

// 把SocketChannel注册到Selector,并关注OP_READ事件

// socketChannel.register(selector, SelectionKey.OP_READ);

eventLoop.register(socketChannel, SelectionKey.OP_READ);

}

}

}

}

}

package io.netty.example.helloworld;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.ClosedChannelException;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.SocketChannel;

import java.nio.channels.spi.SelectorProvider;

import java.util.Arrays;

import java.util.Iterator;

import java.util.Set;

/**

  • @author JavaEdge

  • @date 2021/5/25

*/

public class EventLoop implements Runnable {

private Selector selector;

private Thread thread;

public EventLoop() throws IOException {

this.selector = SelectorProvider.provider().openSelector();

this.thread = new Thread(this);

this.thread.start();

}

/**

  • 把 channel 注册到 事件查询器

*/

public void register(SocketChannel channel, int keyOps) throws ClosedChannelException {

channel.register(selector, keyOps);

}

@Override

public void run() {

while (!Thread.interrupted()) {

try {

// 阻塞方法,等待系统有 I/0 事件产生

int eventNum = selector.select();

System.out.println(“系统发生IO事件 数量->” + eventNum);

Set keySet = selector.selectedKeys();

Iterator iterable = keySet.iterator();

while (iterable.hasNext()) {

SelectionKey key = iterable.next();

iterable.remove();

// 可读事件

if (key.isReadable()) {

SocketChannel socketChannel = (SocketChannel) key.channel();

ByteBuffer buffer = ByteBuffer.allocate(1024);

try {

int readNum = socketChannel.read(buffer);

if (readNum == -1) {

System.out.println(“读取结束,关闭 socket”);

key.channel();

socketChannel.close();

break;

}

// 将Buffer从写模式切到读模式

buffer.flip();

byte[] bytes = new byte[readNum];

buffer.get(bytes, 0, readNum);

System.out.println(new String(bytes));

/* byte[] response = “client hello”.getBytes();

// 清理了才可以重新使用

buffer.clear();

buffer.put(response);

buffer.flip();

// 该方法非阻塞的,如果此时无法写入也不会阻塞在此,而是直接返回 0 了

socketChannel.write(buffer);

*/

// 在 key 上附加一个对象

key.attach(“EventLoop says hello to client”.getBytes());

// 把 key 关注的事件切换为写

key.interestOps(SelectionKey.OP_WRITE);

} catch (IOException e) {

System.out.println(“读取时发生异常,关闭 socket”);

// 取消 key

key.channel();

}

}

if (key.isWritable()) {

SocketChannel socketChannel = (SocketChannel) key.channel();

// 可写时再将那个对象拿出来

byte[] bytes = (byte[]) key.attachment();

key.attach(null);

System.out.println(“可写事件发生 写入消息” + Arrays.toString(bytes));

if (bytes != null) {

socketChannel.write(ByteBuffer.wrap(bytes));

}

// 写完后,就不需要写了,就切换为读事件 如果不写该行代码就会死循环

key.interestOps(SelectionKey.OP_READ);

}

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

启动之后,开启一个客户端连接请求:

打断点到该行代码:

点击继续执行时,dump此时的线程状态:主线程已经阻塞在此

说明主线程在等待 @574线程的锁,它是谁呢?没错

EventLoop 线程阻塞在select 方法,而且它此时已经获取了Selector 内部的一把锁,所以不是Blocked状态。

但此时主线程执行 register 也需要该Selector内部的这把锁,但又不是同一线程,所以产生死锁。

所以不能由main 线程调用注册方法。

2.2 解决死锁


改造后的 EventLoop 类:

package io.netty.example.helloworld;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.ClosedChannelException;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.SocketChannel;

import java.nio.channels.spi.SelectorProvider;

import java.util.Arrays;

import java.util.Iterator;

import java.util.Queue;

import java.util.Set;

import java.util.concurrent.LinkedBlockingDeque;

/**

  • @author JavaEdge

  • @date 2021/5/25

*/

public class EventLoop implements Runnable {

private Selector selector;

private Thread thread;

private Queue taskQueue = new LinkedBlockingDeque<>(32);

public EventLoop() throws IOException {

this.selector = SelectorProvider.provider().openSelector();

this.thread = new Thread(this);

this.thread.start();

}

/**

  • 把 channel 注册到 事件查询器

*/

public void register(SocketChannel channel, int keyOps) {

// 将注册的逻辑封装成一个任务,因为不能让主线程执行,必须由 eventloop 的线程执行

taskQueue.add(() -> {

try {

channel.register(selector, keyOps);

} catch (ClosedChannelException e) {

e.printStackTrace();

}

});

// 但此时EventLoop的线程阻塞在 selector.select(),通过主线程唤醒它

selector.wakeup();

}

@Override

public void run() {

while (!Thread.interrupted()) {

try {

System.out.println(thread + “开始查询 I/O 事件…”);

// 阻塞方法,等待系统有 I/0 事件产生

int eventNum = selector.select();

System.out.println(“系统发生IO事件 数量->” + eventNum);

// 有事件则处理

if (eventNum > 0) {

Set keySet = selector.selectedKeys();

Iterator iterable = keySet.iterator();

while (iterable.hasNext()) {

SelectionKey key = iterable.next();

iterable.remove();

// 可读事件

if (key.isReadable()) {

SocketChannel socketChannel = (SocketChannel) key.channel();

ByteBuffer buffer = ByteBuffer.allocate(1024);

try {

int readNum = socketChannel.read(buffer);

if (readNum == -1) {

System.out.println(“读取结束,关闭 socket”);

key.channel();

socketChannel.close();

break;

}

// 将Buffer从写模式切到读模式

buffer.flip();

byte[] bytes = new byte[readNum];

buffer.get(bytes, 0, readNum);

System.out.println(new String(bytes));

/* byte[] response = “client hello”.getBytes();

// 清理了才可以重新使用

buffer.clear();

buffer.put(response);

buffer.flip();

// 该方法非阻塞的,如果此时无法写入也不会阻塞在此,而是直接返回 0 了

socketChannel.write(buffer);

*/

// 在 key 上附加一个对象

key.attach(“EventLoop says hello to client”.getBytes());

// 把 key 关注的事件切换为写

key.interestOps(SelectionKey.OP_WRITE);

} catch (IOException e) {

System.out.println(“读取时发生异常,关闭 socket”);

// 取消 key

key.channel();

}

}

if (key.isWritable()) {

SocketChannel socketChannel = (SocketChannel) key.channel();

// 可写时再将那个对象拿出来

byte[] bytes = (byte[]) key.attachment();

key.attach(null);

System.out.println(“可写事件发生 写入消息” + Arrays.toString(bytes));

if (bytes != null) {

socketChannel.write(ByteBuffer.wrap(bytes));

}

// 写完后,就不需要写了,就切换为读事件 如果不写该行代码就会死循环

key.interestOps(SelectionKey.OP_READ);

}

}

}

// 无事件则执行任务

Runnable task;

while ((task = taskQueue.poll()) != null) {

// EventLoop执行队列中的任务,即注册任务

task.run();

}

} catch (IOException e) {

e.printStackTrace();

}

}

总结

蚂蚁面试比较重视基础,所以Java那些基本功一定要扎实。蚂蚁的工作环境还是挺赞的,因为我面的是稳定性保障部门,还有许多单独的小组,什么三年1班,很有青春的感觉。面试官基本水平都比较高,基本都P7以上,除了基础还问了不少架构设计方面的问题,收获还是挺大的。


经历这次面试我还通过一些渠道发现了需要大厂真实面试主要有:蚂蚁金服、拼多多、阿里云、百度、唯品会、携程、丰巢科技、乐信、软通动力、OPPO、银盛支付、中国平安等初,中级,高级Java面试题集合,附带超详细答案,希望能帮助到大家。

蚂蚁金服5面,总结了49个面试题,遇到的面试官都是P7级别以上

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

key.attach(null);

System.out.println(“可写事件发生 写入消息” + Arrays.toString(bytes));

if (bytes != null) {

socketChannel.write(ByteBuffer.wrap(bytes));

}

// 写完后,就不需要写了,就切换为读事件 如果不写该行代码就会死循环

key.interestOps(SelectionKey.OP_READ);

}

}

}

// 无事件则执行任务

Runnable task;

while ((task = taskQueue.poll()) != null) {

// EventLoop执行队列中的任务,即注册任务

task.run();

}

} catch (IOException e) {

e.printStackTrace();

}

}

总结

蚂蚁面试比较重视基础,所以Java那些基本功一定要扎实。蚂蚁的工作环境还是挺赞的,因为我面的是稳定性保障部门,还有许多单独的小组,什么三年1班,很有青春的感觉。面试官基本水平都比较高,基本都P7以上,除了基础还问了不少架构设计方面的问题,收获还是挺大的。


经历这次面试我还通过一些渠道发现了需要大厂真实面试主要有:蚂蚁金服、拼多多、阿里云、百度、唯品会、携程、丰巢科技、乐信、软通动力、OPPO、银盛支付、中国平安等初,中级,高级Java面试题集合,附带超详细答案,希望能帮助到大家。

[外链图片转存中…(img-qPD8zowi-1713150317921)]

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
[外链图片转存中…(img-DnH6Uilz-1713150317921)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值