Thread - concurrency issue

放肆的年华 提交于 2020-01-07 09:03:26

问题


Table with column "count". It has primary key "rowID". Now I want to fetch this count, increment it by 1 and update it. I have a scenario where multiple instances / threads try to update the same column - count.

For eg. 3 threads t1,t2,t3 (not synchronised). t1 fetches count(say 0) and increments and updates. Now count would be 1. Now there is a chance that t2 and t3 might try to access the count simultaneously and then issues arise.

Please suggest right way to handle this scenario.


回答1:


This is what database sequences/locks are for. You should use them. However, if you want to use thread synchronization, you have put the 'fetch to update code' in a single synchronized block or method.

Either of the two methods will serve your purpose.

synchronized void method(){

        // fetch
        // increment
        // update

    }

    void method(){

        synchronized (obj) {

            // fetch
            // increment
            // update

        }

    }


来源:https://stackoverflow.com/questions/25743950/thread-concurrency-issue

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