【面试实录01】
面试实录
- META-INF/spring.factories
- 启动命令优先级最高
- 多环境配置
- 1. 定位高CPU进程
- 2. 查看进程内线程CPU
- 3. 线程ID转16进制
- 4. 查看线程堆栈
- 5. 分析代码热点(采样)
- 1. 查看内存分布
- 2. 生成堆转储文件
- 3. 使用MAT分析支配树
- bootstrap.yml
Java面试知识点深度解析(实战进阶版)
一、基础数据类型
深度扩展
-
内存占用与性能优化
• 场景:高并发系统内存优化• 技巧:在数据量大的集合中使用基本类型替代包装类
// 优化前:Integer对象占用16字节(对象头12+数据4)
List list = new ArrayList<>();// 优化后:使用Trove库的TIntArrayList
TIntArrayList optimizedList = new TIntArrayList();
optimizedList.add(100); // 仅占4字节 -
浮点数精度问题
• 场景:金融计算• 解决方案:使用BigDecimal替代double
// 错误示例
double total = 0.1 + 0.2; // 实际结果:0.30000000000000004// 正确做法
BigDecimal a = new BigDecimal(“0.1”);
BigDecimal b = new BigDecimal(“0.2”);
BigDecimal sum = a.add(b); // 精确结果:0.3 -
自动装箱陷阱
• 场景:循环中的性能问题
// 性能陷阱
long start = System.currentTimeMillis();
Long sum = 0L; // 包装类型
for (int i = 0; i < Integer.MAX_VALUE; i++) {
sum += i; // 每次循环触发自动装箱
}
System.out.println(“耗时:” + (System.currentTimeMillis() - start) + “ms”);// 优化方案
long sumPrimitive = 0L; // 基本类型
for (int i = 0; i < Integer.MAX_VALUE; i++) {
sumPrimitive += i; // 无装箱开销
}
二、集合框架
- ConcurrentHashMap深度解析
实现原理:
• JDK8前:分段锁(Segment)
• JDK8+:CAS + synchronized锁桶(Node)
• 场景:高并发计数器
ConcurrentHashMap<String, LongAdder> counter = new ConcurrentHashMap<>();
// 线程安全的计数
counter.computeIfAbsent(“key”, k -> new LongAdder()).increment();
// 比AtomicLong更优:减少CAS竞争
- HashSet实现机制
扩容优化:
// 初始化时设置容量避免扩容
Set largeSet = new HashSet<>(1000000);
// 实际开发场景:用户黑名单系统
Set blacklist = new HashSet<>(loadFromDatabase()); // 初始化加载
- TreeSet高级用法
多级排序:
// 电商商品排序:价格降序,销量升序
Set products = new TreeSet<>(Comparator
.comparing(Product::getPrice).reversed()
.thenComparing(Product::getSales));
// 实际场景:TOP-N查询
products.stream().limit(10).collect(Collectors.toList());
三、线程与线程池
- 线程池最佳实践
生产环境配置:
ThreadPoolExecutor executor = new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors(), // 核心线程数
Runtime.getRuntime().availableProcessors() * 2, // 最大线程数
60, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1000), // 有界队列防止OOM
new CustomThreadFactory(“order-process”), // 自定义线程命名
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
);
// 场景:订单处理系统
executor.submit(() -> processOrder(order));
- CompletableFuture异步编排
场景:聚合多个微服务调用
CompletableFuture userFuture = CompletableFuture.supplyAsync(
() -> userService.getUser(userId), userPool);
CompletableFuture orderFuture = CompletableFuture.supplyAsync(
() -> orderService.getOrder(orderId), orderPool);
userFuture.thenCombine(orderFuture, (user, order) -> {
// 合并结果
return new UserOrderDTO(user, order);
}).exceptionally(ex -> {
// 统一异常处理
log.error(“聚合失败”, ex);
return null;
});
四、动态代理
Spring AOP实现原理
事务管理源码级解析:
// Spring事务代理伪代码
public class TransactionProxy implements InvocationHandler {
private Object target;
private PlatformTransactionManager transactionManager;
public Object invoke(Object proxy, Method method, Object[] args) {TransactionStatus status = null;try {status = transactionManager.begin();Object result = method.invoke(target, args);transactionManager.commit(status);return result;} catch (Exception e) {if (status != null) transactionManager.rollback(status);throw e;}
}
}
// 实际应用:@Transactional注解底层实现
五、消息队列(RocketMQ)
顺序消息实现
场景:订单状态变更
// 保证同一订单的消息顺序
MessageQueueSelector selector = (mqs, msg, arg) -> {
Long orderId = (Long) arg;
int index = (int) (orderId % mqs.size());
return mqs.get(index);
};
producer.send(msg, selector, order.getOrderId());
事务消息流程
// 1. 发送半消息
Message msg = new Message(“order_topic”, “create”, order.toString().getBytes());
SendResult sendResult = producer.sendMessageInTransaction(msg, null);
// 2. 执行本地事务
@Transactional
public boolean executeLocalTransaction(Message msg, Object arg) {
// 数据库操作
return orderDao.create(order) > 0;
}
// 3. 事务状态回查
public LocalTransactionState checkLocalTransaction(MessageExt msg) {
Order order = parseOrder(msg);
return orderDao.exists(order.getId()) ?
LocalTransactionState.COMMIT_MESSAGE :
LocalTransactionState.ROLLBACK_MESSAGE;
}
六、Spring Boot自动装配
自定义Starter开发
步骤:
-
创建配置类
@Configuration
@ConditionalOnClass(RedisTemplate.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
return template;
}
} -
注册自动配置
META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.example.RedisAutoConfiguration
配置优先级实战
启动命令优先级最高
java -jar app.jar --server.port=8081
多环境配置
application-dev.yml > application-prod.yml
七、MySQL索引优化
B+树索引原理
页结构优化:
– InnoDB页结构(默认16KB)
±----------------------+
页头 (56字节) |
---|
虚记录 (固定大小) |
----------------------- |
记录堆 (用户数据) |
----------------------- |
自由空间指针 |
----------------------- |
页目录 (槽位数组) |
----------------------- |
文件尾部 (8字节) |
±----------------------+ |
索引失效场景
-
隐式类型转换
– phone是varchar类型
SELECT * FROM users WHERE phone = 13800138000; – 索引失效 -
函数操作
SELECT * FROM orders WHERE DATE_FORMAT(create_time,‘%Y-%m’) = ‘2023-01’;
– 优化:
SELECT * FROM orders WHERE create_time BETWEEN ‘2023-01-01’ AND ‘2023-01-31’;
覆盖索引优化
– 创建覆盖索引
ALTER TABLE products ADD INDEX idx_category_price (category, price);
– 查询优化
SELECT id, name, price FROM products WHERE category = ‘电子产品’ AND price > 1000;
– 使用覆盖索引,无需回表
八、Linux生产问题排查
CPU飙高诊断
1. 定位高CPU进程
top -c
2. 查看进程内线程CPU
top -Hp
3. 线程ID转16进制
printf “%x\n” <thread_id>
4. 查看线程堆栈
jstack | grep -A 20 <hex_thread_id>
5. 分析代码热点(采样)
profiler.sh -d 30 -f profile.html
内存泄漏排查
1. 查看内存分布
jmap -histo:live | head -20
2. 生成堆转储文件
jmap -dump:format=b,file=heap.bin
3. 使用MAT分析支配树
九、分布式系统关键点
OpenFeign优化实践
@Configuration
public class FeignConfig {
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(100, 5, TimeUnit.MINUTES))
.build();
}
}
// 使用连接池替代短连接
Nacos配置隔离
bootstrap.yml
spring:
cloud:
nacos:
config:
namespace: ${ENV:DEV} # 环境隔离
group: ORDER_SERVICE # 服务分组
十、架构设计思想
Spring Cloud vs Spring Boot
维度 Spring Boot Spring Cloud
定位 快速开发单体应用 构建分布式系统
服务发现 无 Eureka/Nacos/Zookeeper
配置管理 本地配置 集中式配置中心
熔断降级 需手动实现 Hystrix/Sentinel
服务调用 RestTemplate OpenFeign/Ribbon
部署扩展 整体扩缩容 按微服务独立扩缩容
场景选择:
• 内部管理系统:Spring Boot单体应用
• 电商平台:Spring Cloud微服务架构
通过以上深度扩展,您将掌握:
- 集合框架的并发优化与内存管理技巧
- 线程池的定制化配置与异步编排实战
- MySQL索引的底层原理与高级优化策略
- Spring Boot自动装配的源码级理解
- 生产环境问题定位的系统方法论
- 分布式系统设计的核心思想与实践