Q:

Handling many requests in the same time

I have a table Users in MySQL includes 3 fields : ID (int), Name (varchar) and UpdateTime (TimeStamp). 
I have a java web application and one function to get one record in table Users, after that, check if UpdateTime is before current time ---> update UpdateTime by current time plus 2 hours.
And my problem is when having about 100 users access to my app and request to that function to get the same record in the same time, all of them will update UpdateTime. But I want only first user update UpdateTime, latecomers will only get data without update UpdateTime.
How I can do it? I really have no idea.
Thanks.
P/s: Sorry about my English, it seems to be not good :(

A:

Your update time code should be in synchronised block.
Take write lock on your object and if someone has consumed lock before going on update operation and at the same time another request comes should get the pre loaded/after update data.
Chech synchronised keyword in java also check read write lock mechanism. This might help you.
following code might help you.
import java.util.Map;
import java.util.HashMap;

public class Test {
    boolean isWriteLockTaken;
    Map<Integer,String> cachedUsers = new HashMap<Integer,String>();  

    public static void main(String[] args) throws Exception {
        Test t = new Test();
        for(int i=0;i<10;i++){
            t.updateAndGetUser(1);
        }
    }

    public String updateAndGetUser(Integer id) throws InterruptedException {
        if(isWriteLockTaken && !cachedUsers.containsKey(id)){
            this.wait();
        }

        if(!cachedUsers.containsKey(id)){
            isWriteLockTaken = true;
            synchronized(id){
                if(id==1){
                    // do processing to retrive user
                    System.out.println("Updating & loading user");
                    cachedUsers.put(id, "Gaurav");
                    return "Gaurav";
                }
            }
            isWriteLockTaken = false;
        }
        System.out.println("returning from cached list, not loading user details as it is already loaded");
        return cachedUsers.get(id);
    }

}

Thanks, 
Gaurav

