Search code examples
javaprocessing-efficiency

Check if time has passed most efficient t alternative Storing threads on a hashmap or using nanoTime()


I am currently doing a big Java project that involves handling multiple requesta from different users and I would like to know what way is more efficient for handling a wait time. For example: user A cannot press the button in 5 seconds.

First alternative: Have a hashmap where I store the user ID with the thread ID. Then start a thread to run a command in x time. The command is remove A from hashmap.If user A clicks the button it checks if hashmap contains he's ID and then cancellation the event. If I wanted to remove him sooner I have the thread ID stored.

Second alternative: Have a hashmap with user ID and nanoTime + 5sec. If hashmap time value is greater than actual time then button cannot be pressed. Then user ID is removed.

If you can think of any other way efficiency wise it is welcome.


Solution

  • The first way is definitely bad, threads are expensive and there is no good reason to use this approach here.
    You could go with the second approach, but don't use nanoTime unless you need to. It seems like System.currentTimeMillis() would be sufficient. Also, if this is a multi-threaded application (sounds like it is), synchronize access methods to your map or, better yet, use a ConcurrentMap. You may want to store the original timestamp, add the wait time when you check -- it's just cleaner design IMO. You can have a single thread periodically cleaning this map.
    Finally, if this is a web application, you could simply attach the timestamp to the user session. I think it should be possible with pretty much every servlet container and server platform.