How to synchronize a java method called by PL/SQL

孤街浪徒 提交于 2020-01-30 08:09:52

问题


I just have a problem relative to concurrency whose logic flow is when a client (called Oracle Forms) will submit a request (called concurrent program ) and call a plsql procedure, this procedure eventually will call a java static method.

What I find is that when I submit two request in the same time or in a very short interval(like 1 second), some concurrency problem will be noticed.

The java method is the start point of doing something that search from the database suggest that which records should be inserted into database.

The problem is that, they will result in duplicated result since when I query, both request find it fine to insert new records.

I tried add synchronized in the static java method, but this does not solve this problem, why?

What I do is:

public static synchronized void execute

Please note that the insert will be called in plsql, which means I do a not sufficient synchronize if only synchronize the java method. But when I look into the log, it shows the two request run in the same second, which I do not think it is normal! since query database and doing the suggestion is time consuming.

To make the java method really time consuming, I add a code call Thread.sleep(5000), and log for the time after this code and log the thread id.

Surprise to see that the Thread id is 1! And also, the time where they pass the sleep is in the same time. Why is that?

What can I do to solve the problem? Any lock on the java method or pl sql?

PS: I am now trying to use DMBS_LOCK, and which seems to be working but I still hope to know the reason why the java method is not synchronized.


回答1:


I have no idea how the JVM inside the Oracle DB is implemented, but since (at least in some common configurations) every database connection gets its own server process, then if a separate JVM is embedded into each of those, a synchronized block won't do you much good. You'd need to use database locks.




回答2:


  1. Assuming that the calls to the Java static method are done within the same classloader, then synchronized is all you need.

  2. Your logging may be faulty. How exactly are you logging?

  3. Your statement about the database lookup being "time consuming" is not convincing. Databases tend to cache data, for example.

In a nutshell: if, by your definition, an "atomic operation" is a combination of lookup + insert, then you should "synchronize" over both. Acquiring a database lock seems like a reasonable way to go about it.



来源:https://stackoverflow.com/questions/24302726/how-to-synchronize-a-java-method-called-by-pl-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!