title: How can I make this thread safe?
body: <p>I have a server that receives various xml messages from clients (one thread per client) and routes the messages to different functions depending on the message type. Eg. if the first element in the messages contains the string 'login' it signifies that this is a login message so route the message to the login() function.</p>
  
  <p>Anyway, I want to make this message so things don't get messed up if multiple clients are connected and the dispatcher switches threads in middle of the message routing. So here is how I am routing the messages -</p>
  
  <pre><code>public void processMessagesFromClient(Client client)
  {
      Document message;
  
      while (true)
      {
          try
          {
              message = client.inputStream.readObject();
  
              /*
               * Determine the message type
               */
              String messageType = getMessageType(message);
  
              // Route the message depending on its type
              switch (messageType)
              {
                  case LOGIN:
                      userModel.handleLogin();
                  ...
                  ...
                  ...
                  etc...
               }
          } catch(Exception e) {}
     }
  </code></pre>
  
  <p>So how can I make this thread safe? I figure I need to put a synchronise statement in somewhere but Im not sure where. Also Ive been reading around on the subject and I found this post which says there is an issue with using synchronise on 'this' -
  <a href="https://stackoverflow.com/a/416198/1088617">https://stackoverflow.com/a/416198/1088617</a></p>
  
  <p>And another post here which says singletons aren't suitable for using synchronise on (My class in the code above is a singleton) - <a href="https://stackoverflow.com/a/416202/1088617">https://stackoverflow.com/a/416202/1088617</a></p>