Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronization doubt

 
Vishwanath Krishnamurthi
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys ,

I thought of something and am not sure if my understanding is right...


ONE: (When no synchroniztion is done )


If my servlet has one method (methodA) to iterate and display form 1 to 10 and another method (methodB) to iterate and display from 50 to 60 is it very much possible that the page might display:

1
2
3
50
51
4
5


and so on? (when it gets multiple requests)


TWO: (when no synchronization is done)

I looked up the PrintWriter documentation and found that println() is not synchronized.
So does it mean that if I have a method (methodA) with pw.println("Hello");
and another method (methodB) with printWriter.println("Welcome")

I might get an output like this : HeWelcomello

?

Thanks,
Vishwa
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If my servlet has one method (methodA) to iterate and display form 1 to 10 and another method (methodB) to iterate and display from 50 to 60 is it very much possible that the page might display:


Each request has its own Thread so the output will not be mixed up IF (big if) you do not use instance variables.

Bill
 
Vishwanath Krishnamurthi
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, each request would have its own thread...
...say request1 goes to ThreadA and results in the invocation methodA()
and request2 goes to ThreadB and results in the invocation of methodB()

my question is,
is there a possibility for this kind of execution:

ThreadA started,
ThreadA half way through methodA()
ThreadB started, runs, completes...
ThreadA resumes, runs, completes...

if so, wouldnt it cause a mix up in the output?
 
Mohamed Inayath
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it is synchroized no..
ThreadA will finish then only the the lock will be opened for ThreadB to execute the method.

If its not Synchronized and the class has instance variable and used with the common method then you land up in trouble.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64698
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without thread problems, such as instance variables, there is no possibility for "output mixup" because each thread will be responding with its own response.
 
Vishwanath Krishnamurthi
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
^
Hi,
thanks...
that was where I was getting confused
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic