Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

java - Thread - concurrency issue

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

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

1 Reply

0 votes
by (71.8m points)

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

        }

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...