同步数据库访问
我在应用程序中使用数据库,我需要同步访问数据库,例如当我的应用程序启动两个线程正在访问数据库时,如何避免这种情况?
private synchronized Database accessDB()
{
Database dbObj = null;
try {
_uri = URI.create(dbLocation + DB_NAME);
try {
dbObj = DatabaseFactory.openOrCreate(_uri, new DatabaseSecurityOptions(false));
System.out.println("Database Created"+_dbTopNews);
} catch (ControlledAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DatabaseIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DatabasePathException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dbObj;
}
上述方法在调试时将对象返回给第一个线程,但在访问第二个线程时返回 null
A Y
I am using database in my application, I have requirement to access database synchronously, for example when my application starts two threads are accessing the database, how can I avoid this situation?
private synchronized Database accessDB()
{
Database dbObj = null;
try {
_uri = URI.create(dbLocation + DB_NAME);
try {
dbObj = DatabaseFactory.openOrCreate(_uri, new DatabaseSecurityOptions(false));
System.out.println("Database Created"+_dbTopNews);
} catch (ControlledAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DatabaseIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DatabasePathException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dbObj;
}
te above method when debugging returns object to first thread, but it is returning null when second thread is accessed
A Y
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,有两种方法可以做到这一点,具体取决于您要进行哪种隔离。
1:交易。这隔离了数据库中的操作。例如,保证一次只有一个线程(会话)可以对表或行进行更改。
2:同步。这是 Java 中在多线程环境中处理线程并发的方法。通过使用同步(和“锁定”),可以隔离代码的各个部分,以便一次只有一个线程可以执行它。
很难更具体地说明您提供的信息。
Generally, there are two ways to do this, depending on which isolation you are after.
1: Transactions. This isolates operations in the database. Guaranteeing, for instance, that only one thread (session) at a time can make changes to a table or a row.
2: Synchronization. This is the method in Java by which thread concurrency is handled in a multithreaded environment. By using synchronization (and "locking"), sections of your code can be isolated so that only one thread at a time may execute it.
Hard to be more specific with the information you provided.