Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
163 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

        }

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...