
本文深入探讨了在Java多线程环境中,如何安全有效地管理共享的SMPP会话并发送大量消息。通过分析一个常见的`wait/notify`同步误用案例,我们揭示了导致`ArrayIndexOutOfBoundsException`的根本原因。文章将详细阐述`wait/notify`机制的正确用法,并引入Java并发包中的`ReentrantLock`、`Condition`以及`BlockingQueue`等高级工具,提供一种更健壮、更清晰的解决方案,以实现发送者线程与会话守护线程之间的协同工作,确保会话状态的正确同步和消息的可靠发送。
在并发编程中,当多个线程需要访问和修改同一个共享资源时,必须采取适当的同步措施来避免数据不一致或运行时异常。本教程将以一个发送短信的场景为例,深入探讨Java中多线程同步的常见陷阱及最佳实践。
假设我们有一个系统,需要通过SMPP协议发送大量短信。为了提高吞吐量,我们计划使用多个线程(Sender)并行发送消息。同时,由于SMPP会话可能会因网络问题中断,我们需要一个独立的“守护”线程(SessionProducer)来负责检测会话状态并在必要时重新建立连接。SMPPSession对象是所有线程共享的,它包含了发送消息和重新绑定会话的方法。
核心需求如下:
立即学习“Java免费学习笔记(深入)”;
以下是原始实现的关键代码片段:
// SMPPSession 模拟类
public class SMPPSession {
private volatile boolean bind = false; // 使用volatile确保可见性
// ... 其他方法 ...
public synchronized int sendMessage(String msg){ /* ... */ return 1; }
public synchronized void reBind(){ /* ... */ this.bind = true; /* ... */ }
public synchronized boolean isBind(){ return this.bind; }
}
// Sender 线程
public class Sender extends Thread{
private SMPPSession smppSession;
// ... 构造函数 ...
@Override
public void run(){
while (!Client.messages.isEmpty()){ // 问题点1: 外部非同步检查
synchronized (Client.messages){ // 同步块
if (smppSession.isBind()){
final String msg = Client.messages.remove(0); // 问题点2: 可能的越界访问
smppSession.sendMessage(msg);
Client.messages.notifyAll(); // 问题点3: 通知对象不合适
} else {
try {
Client.messages.wait(); // 问题点4: 等待对象不合适
} catch (InterruptedException e) { /* ... */ }
}
}
}
}
}
// SessionProducer 线程
public class SessionProducer extends Thread{
private SMPPSession smppSession;
// ... 构造函数 ...
@Override
public void run(){
while (!Client.messages.isEmpty()){ // 问题点1: 外部非同步检查
synchronized (Client.messages){ // 同步块
if (!smppSession.isBind()){
smppSession.reBind();
Client.messages.notifyAll(); // 问题点3: 通知对象不合适
} else{
try {
Client.messages.wait(); // 问题点4: 等待对象不合适
} catch (InterruptedException e) { /* ... */ }
}
}
}
}
}
// Client 主类
public class Client {
public static final List<String> messages = new CopyOnWriteArrayList<>(); // 共享消息列表
public static void main(String[] args) {
// ... 消息填充 ...
SMPPSession smppSession = new SMPPSession();
// ... 启动 SessionProducer 和 Sender 线程 ...
}
}运行上述代码,会观察到ArrayIndexOutOfBoundsException。这是因为:
wait(), notify(), notifyAll() 是Java中用于线程间协作的低级机制,它们必须在synchronized块内部调用,并且作用于同一个对象。
关键原则:
Java并发包(java.util.concurrent)提供了更高级、更灵活的同步工具,如ReentrantLock和Condition,它们是synchronized和wait/notify的替代品,能提供更细粒度的控制。
我们将使用ReentrantLock来保护SMPPSession的内部状态,并使用Condition来管理线程对会话绑定状态的等待和通知。
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class SMPPSession {
private volatile boolean bind = false;
private final ReentrantLock sessionLock = new ReentrantLock();
private final Condition sessionBoundCondition = sessionLock.newCondition(); // 用于等待会话绑定
private static final Random idGenerator = new Random();
public int sendMessage(String msg) {
sessionLock.lock(); // 获取会话锁
try {
while (!bind) { // 循环检查会话是否绑定
System.out.println(Thread.currentThread().getName() + " 发现会话未绑定,等待...");
sessionBoundCondition.await(); // 释放锁并等待
}
// 会话已绑定,可以发送消息
System.out.println("Sending message: " + msg);
Thread.sleep(100); // 模拟发送耗时
return Math.abs(idGenerator.nextInt());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println(Thread.currentThread().getName() + " 发送消息时被中断.");
return -1;
} finally {
sessionLock.unlock(); // 释放会话锁
}
}
public void reBind() {
sessionLock.lock(); // 获取会话锁
try {
System.out.println("Rebinding...");
Thread.sleep(1500L); // 模拟重新绑定耗时
this.bind = true;
System.out.println("Session established!");
sessionBoundCondition.signalAll(); // 通知所有等待会话绑定的线程
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Rebind操作被中断.");
} finally {
sessionLock.unlock(); // 释放会话锁
}
}
// 提供一个方法让外部可以设置会话为未绑定状态,模拟连接断开
public void setUnbound() {
sessionLock.lock();
try {
this.bind = false;
System.out.println("SMPPSession: 会话状态设置为未绑定.");
} finally {
sessionLock.unlock();
}
}
public boolean isBind() {
sessionLock.lock(); // 读取也需要加锁,确保可见性和原子性
try {
return this.bind;
} finally {
sessionLock.unlock();
}
}
}解释:
对于生产者-消费者模式,Java提供了BlockingQueue接口,它是线程安全的,并且自带了等待/通知机制,无需手动实现wait/notify。
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
// Sender 线程 (使用BlockingQueue)
public class Sender extends Thread {
private final SMPPSession smppSession;
private final BlockingQueue<String> messageQueue;
private final AtomicBoolean running; // 用于控制线程生命周期
public Sender(String name, SMPPSession smppSession, BlockingQueue<String> messageQueue, AtomicBoolean running) {
this.setName(name);
this.smppSession = smppSession;
this.messageQueue = messageQueue;
this.running = running;
}
@Override
public void run() {
try {
while (running.get() || !messageQueue.isEmpty()) { // 只要还在运行或队列非空就继续
String msg = messageQueue.poll(100, TimeUnit.MILLISECONDS); // 尝试获取消息,等待100ms
if (msg == null) {
// 如果短时间内没有消息,且主程序已发出停止信号,则退出
if (!running.get() && messageQueue.isEmpty()) {
break;
}
continue; // 继续循环,等待新消息或退出信号
}
int msgId = smppSession.sendMessage(msg);
if (msgId != -1) {
System.out.println(Thread.currentThread().getName() + " sent msg and received msgId: " + msgId);
} else {
// 发送失败,可以考虑将消息重新放回队列头部进行重试
System.err.println(Thread.currentThread().getName() + " failed to send message: " + msg + ", re-adding to queue.");
messageQueue.put(msg);以上就是Java多线程环境下SMPP会话与消息发送的同步机制优化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号