【发布时间】:2015-03-24 13:39:16
【问题描述】:
我正在使用 Java 和 mysql 作为数据库,但遇到了一个奇怪的问题: 我的一个客户的连接非常不稳定,有时丢包率可能很高。好吧,我知道这不是软件的错,但我去那里测试,当程序调用“DriverManager.getConnection()”并且网络连接变得不稳定时,该行会锁定应用程序(或给定线程)几分钟.我当然添加了一些逻辑来使用另一个数据源在本地缓存数据,然后尽可能保存到网络主机,但是,我不能经常让程序挂起超过 10 秒(而且这种方法似乎没有任何超时规范)。 所以,我想出了一个这样的解决方法:
public class CFGBanco implements Serializable {
public String driver = "com.mysql.jdbc.Driver";
public String host;
public String url = "";
public String proto = "jdbc:mysql://";
public String database;
public String user;
public String password;
}
private static java.sql.Connection Connect(HostConfig dataHost) throws java.sql.SQLException, ClassNotFoundException
{
dataHost.url = dataHost.proto+dataHost.host;
if(dataHost.database != null && !dataHost.database.equals("")) dataHost.url += "/"+dataHost.database;
java.lang.Class.forName(dataHost.driver);
ArrayList<Object> lh = new ArrayList<>();
lh.add(0, null);
Thread ConThread = new Thread(()-> {
try {
lh.add(0, java.sql.DriverManager.getConnection(
dataHost.url, dataHost.user, dataHost.password));
} catch(Exception x ) {
System.out.println(x.getMessage());
}
}, "ConnThread-"+SessId);
ConThread.start();
Thread TimeoutThread = new Thread(() -> {
int c = 0;
int delay = 100;
try {
try {
do {
try {
if(t.isAlive())
Thread.sleep(delay);
else
break;
} catch(Exception x) {}
} while((c+=delay) < 10000);
} catch(Exception x){}
} finally {
try {
t.stop();
} catch(Exception x){}
}
}, "ConTimeout-"+SessId);
TimeoutThread.start();
try {
ConThread.join();
} catch(Exception x) {}
if(lh.get(0) == null)
throw new SQLException();
return (Connection) lh.get(0);
}
我从另一个线程调用 getConnection,然后创建一个辅助“超时”线程来观察它,然后将调用线程加入 ConThread。 确实,我得到的结果接近预期,但这让我想知道: 有一个更好的方法吗?创建 2 个线程是否会占用大量系统资源,足以使这种方法不切实际?
【问题讨论】:
标签: java mysql multithreading