SQLite in a multithreaded java application

社会主义新天地 提交于 2019-11-27 19:25:59
thkala

This is an issue with the core SQLite library - not with any Java wrapper. SQLite uses filesystem-based locks for concurrent access synchronization among processes, since as an embedded database it does not have a dedicated process (server) to schedule operations. Since each thread in your code creates its own connection to the database, it is treated as a separate process, with synchronization happening via file-based locks, which are significantly slower than any other synchronization method.

In addition, SQLite does not support per-row locking (yet?). Essentially the whole database file becomes locked for each operation. If you are lucky and your filesystem supports byte-range locks, it may be possible for multiple readers to access your database simultaneously, but you should not assume that kind of behavior.

The core SQLite library by default allows multiple threads to use the same connection concurrently with no problem. I presume that any sane JDBC wrapper will allow that behavior in Java programs as well, although I have not actually tried it.

Therefore you have two solutions:

  • Share the same JDBC connection among all threads.

  • Since the SQLite developers seem to think that threads are evil, you would be better off having one thread handle all your database operations and serialize DB tasks on your own using Java code...

You might want to have a look at this old question of mine - it seems to have accumulated several tips on improving update performance in SQLite over time.

I use the same connection for multiple threads. in addition I had to make db-write methods synchronized, otherwise I still get bussy error

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