• Post Reply Bookmark Topic Watch Topic
  • New Topic

Multi Threaded operations

 
Rahul Dayal Sharma
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

If I have a multi threaded operation such as a server and client, I would generally place synchronized on my method(s) on the server to ensure that the data does not change dynamically by multiple users at the same time (i.e., to maintain consistency) but when I do make the method(s) synchronized, what all repercussions may that have when multiple clients try to call the same method at the same time ?
 
Junilu Lacar
Sheriff
Posts: 10020
119
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The topic of concurrency is quite large and there are many nuances that would apply to a question as general as this. Let me just say that generally, you wouldn't synchronize your methods in classes used on a server side application. There are more performant design choices that you can make to avoid concurrency problems. For example, using immutable classes and not having instance variables and/or shared global (static) variables in your classes are better alternatives in guarding against concurrency problems.

I will move this topic to the Threads and Synchronization forum.
 
Rahul Dayal Sharma
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see, but what if I'm after a distributed approach with multiple clients accessing the server at the same time. Wouldn't I require a separate thread for each client to keep them connected to the server process, as in a queue ?

I'm curious about threading about socket programming, hence my question.
 
Junilu Lacar
Sheriff
Posts: 10020
119
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're rolling your own server, the usual approach is to have a main socket/thread listening for connections, then give each client a "worker" socket/thread to use to complete the rest of the request. Here's one article that describes this in detail: http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html

If you're using a framework that already takes care of this stuff, then the classes that you write are normally written without synchronized methods. This is because synchronization is expensive and on the server side, it can have a significant impact on the performance of your server application. Your class designs should then avoid having any kind of shared and persistent state in them if they are to be used in the context of one of these worker threads. Otherwise, you will have to synchronize your methods that access shared variables.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!