0

suppose I have a service written in Java:

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

Then I deploy this piece of code to a service (one instance). Suppose multiple users are using this server the same time, try to run this main function the same time. (Note: there is no explicit specification of using multi-threads)

  1. Will this main method be executed the same time by multiple users?
  2. Or the server has to accept users requests in a sequence and process the request one by one, and then, actually only one user can call the main method at a time.

I think 1. is false and 2. is true, right? Thanks

lightrek
  • 951
  • 3
  • 14
  • 30
  • 3
    There is no absolute true or false answer, it entirely depends on how you write the code. For example, each user/connection could create a new instance of your HelloWorld class, and each could quite easily run it at the same time depending on your thread structure. This would be a suitable solution for a low user count, but may not hold up well for high user counts. It entirely depends on what you are trying to achieve, and if one users actions/requests should influence another users results? Question 2 is typically true, but it all depends on how you write the code and thread pool. – sorifiend Mar 09 '22 at 01:50
  • Thanks. @sorifiend, my question only considers one instance of the HellowWorld class. In this case, can this main method be executed the same time by multiple users? – lightrek Mar 09 '22 at 04:21
  • 1
    Yes, depending on how your code operates it can work on a single instance just fine (much like multiple simultaneous database requests for the same information at the same time). However, things get messy when you try to change data or update values as a result of the call/request, or if the value you want to return may be changed by a background task/thread, because then you really need to start considering thread safety and locks which means limiting access to the class/method to one thread at a time to prevent unexpected behaviour. – sorifiend Mar 09 '22 at 04:48
  • 1
    Consider what happens if your method accesses a file in the background or performs some IO request, it could very well fail if two separate users attempt to do it at the same time, and a thread lock or some sort of queue would be needed. I don't actually know if there are any issues having multiple threads try to print to the output at the same time, but see: https://stackoverflow.com/questions/9459657/is-multi-thread-output-from-system-out-println-interleaved – sorifiend Mar 09 '22 at 04:50

0 Answers0