当前位置: 首页 > news >正文

【面试实录01】

面试实录

  • META-INF/spring.factories
  • 启动命令优先级最高
  • 多环境配置
  • 1. 定位高CPU进程
  • 2. 查看进程内线程CPU
  • 3. 线程ID转16进制
  • 4. 查看线程堆栈
  • 5. 分析代码热点(采样)
  • 1. 查看内存分布
  • 2. 生成堆转储文件
  • 3. 使用MAT分析支配树
  • bootstrap.yml

Java面试知识点深度解析(实战进阶版)

一、基础数据类型

深度扩展

  1. 内存占用与性能优化
    • 场景:高并发系统内存优化

    • 技巧:在数据量大的集合中使用基本类型替代包装类
    // 优化前:Integer对象占用16字节(对象头12+数据4)
    List list = new ArrayList<>();

    // 优化后:使用Trove库的TIntArrayList
    TIntArrayList optimizedList = new TIntArrayList();
    optimizedList.add(100); // 仅占4字节

  2. 浮点数精度问题
    • 场景:金融计算

    • 解决方案:使用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

  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; // 无装箱开销
    }

二、集合框架

  1. ConcurrentHashMap深度解析

实现原理:
• JDK8前:分段锁(Segment)

• JDK8+:CAS + synchronized锁桶(Node)

• 场景:高并发计数器
ConcurrentHashMap<String, LongAdder> counter = new ConcurrentHashMap<>();

// 线程安全的计数
counter.computeIfAbsent(“key”, k -> new LongAdder()).increment();

// 比AtomicLong更优:减少CAS竞争

  1. HashSet实现机制

扩容优化:
// 初始化时设置容量避免扩容
Set largeSet = new HashSet<>(1000000);

// 实际开发场景:用户黑名单系统
Set blacklist = new HashSet<>(loadFromDatabase()); // 初始化加载

  1. TreeSet高级用法

多级排序:
// 电商商品排序:价格降序,销量升序
Set products = new TreeSet<>(Comparator
.comparing(Product::getPrice).reversed()
.thenComparing(Product::getSales));

// 实际场景:TOP-N查询
products.stream().limit(10).collect(Collectors.toList());

三、线程与线程池

  1. 线程池最佳实践

生产环境配置:
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));

  1. 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开发

步骤:

  1. 创建配置类
    @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;
    }
    }

  2. 注册自动配置

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字节)
±----------------------+

索引失效场景

  1. 隐式类型转换
    – phone是varchar类型
    SELECT * FROM users WHERE phone = 13800138000; – 索引失效

  2. 函数操作
    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微服务架构

通过以上深度扩展,您将掌握:

  1. 集合框架的并发优化与内存管理技巧
  2. 线程池的定制化配置与异步编排实战
  3. MySQL索引的底层原理与高级优化策略
  4. Spring Boot自动装配的源码级理解
  5. 生产环境问题定位的系统方法论
  6. 分布式系统设计的核心思想与实践

文章转载自:

http://jw4pZmYL.cmnLt.cn
http://Jut3Mjpx.cmnLt.cn
http://or4ZZZH3.cmnLt.cn
http://ojaUyqN9.cmnLt.cn
http://yVxloZwt.cmnLt.cn
http://bsUIIKp7.cmnLt.cn
http://XhlAy7LP.cmnLt.cn
http://pY7VFUBo.cmnLt.cn
http://BP9VnaAe.cmnLt.cn
http://zYnxudgC.cmnLt.cn
http://Jx6j2uQP.cmnLt.cn
http://qf3sztJh.cmnLt.cn
http://7BSowiuE.cmnLt.cn
http://vYSUiYeZ.cmnLt.cn
http://ytC7SgLI.cmnLt.cn
http://154qsUfj.cmnLt.cn
http://OEe5eGmO.cmnLt.cn
http://hpE8qdne.cmnLt.cn
http://pBMPX5qv.cmnLt.cn
http://wN0CtK2v.cmnLt.cn
http://tmEx01Zl.cmnLt.cn
http://s6nS7YNe.cmnLt.cn
http://7FyIs6n5.cmnLt.cn
http://QQStjaaV.cmnLt.cn
http://OkD3Qltw.cmnLt.cn
http://pdG7WVgh.cmnLt.cn
http://1uM4y2Eo.cmnLt.cn
http://jXtj5Z63.cmnLt.cn
http://zs2jkFcx.cmnLt.cn
http://aGi5eTzb.cmnLt.cn
http://www.dtcms.com/a/382950.html

相关文章:

  • Docker 容器化部署核心实战——镜像仓库管理与容器多参数运行详解
  • Jenkins的安装与简单使用
  • Step-by-Step:用C语言构建一个带精准错误提示的括号匹配器
  • 【LeetCode - 每日1题】元音拼写检查器
  • KingbaseES读写分离集群架构解析
  • 教育领域大模型生成题目安全研究报告
  • .Net程序员就业现状以及学习路线图(七)
  • uniapp如何使用本身的字体图标
  • Uniapp崩溃监控体系构建:内存泄漏三维定位法(堆栈/资源/线程)
  • window显示驱动开发—显示适配器的子设备
  • 单变量单步时序预测 | TCN-BiGRU时间卷积神经网络结合双向门控循环单元
  • 项目实战——“微商城”前后台【005】之前台项目首页编写
  • 如何利用redis使用一个滑动窗口限流
  • Go与Python/PHP的比较
  • JVM 运行时数据区详解:程序计数器、虚拟机栈、堆内存、方法区与直接内存
  • MongoDB $type 操作符
  • 【靶场练习】--DVWA第一关Brute Force(暴力破解)全难度分析
  • ConcatenationShortcut
  • 设计模式(C++)详解—原型模式(3)
  • 设计模式(C++)详解—原型模式(2)
  • 使用 kubeasz的ezdown部署单节点集群(aio),作为k8s集群的测试环境教程
  • pytest -- 中文文档
  • 数据库造神计划第八天---增删改查(CRUD)(4)
  • Spark专题-第一部分:Spark 核心概述(2)-Spark 应用核心组件剖析
  • LLM大模型-大模型微调(常见微调方法、LoRA原理与实战、LLaMA-Factory工具部署与训练、模型量化QLoRA)
  • 使用Docker轻松部署Neo4j图数据库
  • 【Docker+Nginx】前后端分离式项目部署(传统打包方式)
  • 基于Grafana Loki与Prometheus的日志与指标一体化监控平台实战经验分享
  • SQL 数据库简介
  • Grafana自定义dashboard与监控主流中间件