r/javahelp • • Jul 24 '21

Unsolved [Concurrency] What will you do if multiple users access your application at the same time?

I'm an experienced Software Engineer but very weak in concurrency because of no prior experience in that. I've been interviewing with several companies in which I was asked similar kind of questions as given below:

  1. If you are designing a fantasy sports application in which there's a contest which can handle only 100 users. If 99 users are already registered for the contest and multiple users hit the PARTICIPATE button at the same time to become the 100th user, then how will you handle this in your application?

  2. If you are designing a chess game, where multiple users are selecting the users of same level of competence to play with them. Then suppose at same time, users A and B choose the user C (to play with) at the same time, then how will you handle this?

I usually answer this by saying that I'll use synchronized block in Java or on Database side, I'll use Locking concept. But I'm not sure of either of them. So, can anyone tell here how do you answer such questions? Should one answer this in terms of Java Multithreading or DBMS or both? Please can anyone also tell me any resources to understand the theory to answer such type of questions or any website or YouTube channel where solutions are given to these kind of questions?

16 Upvotes

11 comments sorted by

•

u/AutoModerator Jul 24 '21

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

6

u/ignotos Jul 24 '21

I'll use synchronized block in Java or on Database side, I'll use Locking concept

I think that's fine. One thing to consider is whether there is only one server (in which case synchronizing inside the Java code is probably fine), or there might be multiple server instances running (in which case it's probably better to use the database).

You could perhaps read up on some specific techniques like optimistic locking or queueing.

2

u/WarWithSelf Jul 24 '21

Thanks for your answe. But can you please tell me the reason behind why we synchronize Java code in case of one server and why we use DB in case of multiple servers? Apologies if this question sound stupid, but I don't have an idea of why it should be done that way.

6

u/sweetno Jul 24 '21
  1. Synchronizing code in Java is faster.

  2. You can't use synchronized code between multiple servers, so a DB locking can be a workaround.

5

u/ignotos Jul 24 '21

If you have multiple servers, then synchronizing in the Java code is not enough - if the users are each talking to different server instances, then each server might independently decide that they have "won the race".

But the database is centralized, and if the servers use the database's concurrency mechanisms to resolve the race then it will ensure that only one user "wins" even if there is traffic coming in to multiple servers simultaneously.

4

u/[deleted] Jul 24 '21 edited Jul 24 '21

You have to be very careful with locking, because it if you do it wrong, it can slow down your application or cause deadlocks (if you order your locks incorrectly). Another problem with locks, especially synchronized blocks, is that they are limited to one JVM. If your application is deployed to the cloud, you might have multiple instances of your application running to be able to handle more user traffic, so you can't use synchronized in that case.

For example, with databases, there are two common locking strategies: Pessimistic Locking and Optimistic Locking.

  • Pessimistic Locking: the thread locks the row while it completes the operation. But this can have really bad performance consequences. This approach is almost never recommended.

  • Optimistic Locking: the thread checks a version number. When the thread is done and ready to commit the changes to the database, and sees that the version number changed, the thread either aborts or starts over. This requires compensation logic, but has far better performance.

The answer to both of the problems you mentioned are: the first one wins. The question is how you determine "first":

  • If you're using a database, you can use a version number. The first thread to update the version number wins. All the other threads would see that the version number changed, and they lose.

  • With synchronization, the first thread to acquire the lock wins. When the other threads are acquire the lock, they will see that the state changed (100 users have been registered, player C has been chosen already), and they lose. But remember, this only works on a single JVM. If you have multiple JVMs, this won't work.

  • With a message queue, like in memory BlockingQueue or even something fancy like JMS. The queue is like a line, and who is first is literally who is first in line. The nice thing about queues is that while a BlockingQueue has the same problem as a synchronized block, you can run an external "Queue Manager" that can coordinate between JVMs (like Kafka, ActiveMQ, etc.).

1

u/x42bn6 Jul 24 '21

I found this book extremely helpful in teaching me what Java has to offer in terms of concurrency, and wish I'd found this book several years earlier.

Note that this book doesn't really cover multiple-JVM scenarios - that is a discussion for distributed systems (I don't have a book recommendation for this unfortunately - I learnt it all through experience). A cross-JVM lock, for example, is very difficult, but could be achieved with a database or a queueing technology like Kafka. This is also worth learning at some point.

Depending on the roles you are applying to, one could be more important than the other. For example, a business that uses microservices that operate in single-threaded fashion but scales horizontally would be more interested in the latter, but a company that deals with low-latency applications would care about the former.

Both your questions can be solved in multiple ways. In pure Java, you'd have most of the information in memory, and you'd likely use locks in some way. In a distributed system, you might have a message bus (like Kafka) or database that handles the sequencing/locking for you, so you'd need to talk about things like exactly-once delivery or database locking. Then there are systems that will use a combination of both.

1

u/khooke Extreme Brewer Jul 24 '21

If the questions were asked exactly as you have summarized here, I don't think they were looking for a technical answer about concurrency or locking at all. Read the questions again. Both are asking what happens when a user selects to access a limited resource (either to participate in the contest, or to select an available player) - if there are no more contest entries or players available, what happens? I think they're asking how do you communicate this to your user (as someone who has given many technical interviews over the years, this is what I would be looking for with this type of question).

If you answered these questions by immediately jumping into an explanation of concurrency and locking and other techniques, you've already missed the point of the question.

1

u/khooke Extreme Brewer Jul 24 '21

If you started your answer to this with 'well there are two parts to this problem, how to handle the feedback to the user that there are no more contest entries available, and then secondly how I'd implement this on the serverside', then I'd give you bonus points :-)

1

u/Automaton_J Jul 24 '21

If you're making a web application, it would be better to use a framework like Spring. It handles user requests concurrently automatically.

It'd also be excellent for performance if you can learn Spring Webflux

2

u/TheSecondist Jul 24 '21

What you say is true, but it doesn't solve the problem. The example already assumes that there is a way to run user requests concurrently, the problem is, what happens if two people press on the button at thr same time and their two threads both try to get access to the last place of entry. Some form of snychronization is needed, as explained by other comments