• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

basic Thread run synch question

 
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why is the output like this ? the method run() is synchronized, so the output should be arranged in an ascending order. I mean it should print 0 to 9 then again in an oderly fashion and not like below. If the method run() was not synch then it would have been ok but the run method is synchronized.
Thread ONE
0 1 2 3 4 Thread ONE
5 1 2 3 4 5 6 7 8 9 0

public class Test extends Thread {
static int x=0;
public static void main(String args[])
{
Test obj1 = new Test();
Test obj2 = new Test();
obj1.start();obj2.start();
}
public synchronized void run()
{System.out.println("Thread ONE");
for(x=0;x<10;++x)
System.out.print(x+" ");}}
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have created two objects. Then you start two threads , one for each object.
However, each thread is using the System.out PrintWriter object, and that is where you have thread contention.
Try synchronizing on System.out instead of your run method and see what happens.
Rob
 
mark stone
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rob: i have read about synchronizing methods. what do you mean by synchronizing System.out.
can you tell me where to put the synch in the code ?

Originally posted by Rob Ross:
You have created two objects. Then you start two threads , one for each object.
However, each thread is using the System.out PrintWriter object, and that is where you have thread contention.
Try synchronizing on System.out instead of your run method and see what happens.
Rob

 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

By synchronizing on the critical resource (System.out) you ensure that only one thread at a time can write to it completely before another thread starts writing to it as well.
Rob
 
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi mark,
here u had run() synch but the problem was u created two objects of the thread. making method synch means that "if a thread try to access the SAME object invoking the method AND the other thread has locked THAT SHARED OBJECT then it has to block till the lock is released".
if u had instead implemented Runnable and created Test object in main which u had passed to two different encapsulating Thread objects then u 'd have got what u want.
i mean doing like this,
class Test implements Runnable {
public synchronized void run() {
// blah .. blah.. blah..
}
psvm(String[]s) {
Test t = new Test();
Thread th1 = Thread(t);
Thread th2 = Thread(t);
th1.start();
th2.start();
}
}
hope u got what i mean...
regards
maulin.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
here object 't' is a shared object between two threads th1 and th2 and so it's synch method run() can be accessed ONLY by ONE thread at a time. so u get first thread output then second's output (tho order of threads may differ according to systems load. so u might get second thread's o/p first and first thread's after that)
also, "psvm" is "public static void main"
regards
maulin.
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi -
Like Mark, I was very surprised that the original output wasn't sequential. So I ran the original program on Windows 95(JDK1.3) and 8/10 times got the expected sequential output. Then I ran it on NetBSD/i386(java1.1) and got sequential output 10/10 times.
Mark, did you get this example from a mock exam, and if yes, was the question 'what output will result...', and what was the correct answer?
I think the correct answer, at least for the purposes of the Certification exam, should be the sequential output.
It was very astute of Rob to figure out that System.out was being pre-empted - I never would have gotten that. But I also think that in a good installation this SHOULDN'T happen - that it indicates an imperfection in the particular OS &/or java implementation. ok, I'm really in over my head now - am I wrong? - please jump in.
Just curious about whether the exam will test our ability to find what I consider to be a very subtle twist on expected behavior of java threads.
Thanks. Sylvia
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ohhh, I'm astute, excellent
Actually Sylvia, this is exactly the kind of things you can't make predictions about. The very fact that it behaves differently on different platforms is evidence of the non-deterministic nature of multi-threading.
In other words, this is not a "fluke", this is the way it actually works! There's nothing wrong with the way System.out is implemented.
Say you had a white board in a room, and one person was writing on it with a marker. If he had a task, to draw a square, then a triangle, and he always drew them in that order, then an observer looking at just the output of the white board would first see a square appear, then a triangle, every time this person went to the board.
Now suppose another person comes into the room. He also wants to draw a square and a triangle, in that order, on the board. The only problem is, there is only one marker! The two people must share.
So how do they share? Well it could be different every time. Maybe the first person draws his square, then his triangle, and then hands his marker to his friend who also draws both images.
OR maybe the first person just draws a square, then hands over the marker, and goes to get some coffee. In the meantime, the second person diligently keeps drawing his square, triangle, square, triangle, until the first person comes back, picks up the marker, and draws his triangle (since he last drew a square).
The bottom line is, there is no way to predict the outcome of the order in which these two people draw; it can differ each time. That's not a flaw, it's inherent in the design of the system.
Rob
[ January 23, 2002: Message edited by: Rob Ross ]
 
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
Like Rob said you can't predict the output.
And in the cert exam you will have that answer.
You better know about threads, because there is a lot of question about it. And I remember a question of that kind.
 
sylvia weller
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your example Rob. I believe you are
right but something still baffles me.
Wouldn't it be correct that becuase this room is
'synchronized' only one person can be in it any
time, and person2 must wait until person1 leaves
before coming in to use the marker? So there'd
be no grabbing possible, and no coffee breaks.
Each person has enter the room, draw a square,
draw a triangle,and leave, in that order.
How could a person leave the room before both
shapes are completely drawn?
Sorry to beat this to death, but what am I not
understanding? Thank you.
Sylvia
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sylvia,
the situation you are describing would indeed be an example of synchronization in my analogy.
I was trying to highlight the way System.out.print was working in the original application, in it's unsynchronized state.
This is what synchronization provides you : atomicity of actions, ie, ensuring that a person always draws a square, then a triangle, with no breaks in between.
Rob
 
mark stone
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sylvia: you are correct where the confusion is.
BUT in the cert exam what should we answer ?
plain situation:
run is synchronized and it prints out say 5 numbers sequentially.
and say three threads have to run this run method.
what do the sun guys expect us to answer ?
because according to the api only one thread can run a synchronized method. so logically each thread should print out the numbers sequentially. which thread gets to, that depends on the system.
SO WHAT SHOULD WE ANSWER IN THE CERT.
I CAN TELL YOU THEY WOULD EXPECT TO ANSWER THAT OUTPUT IS PRINTED SEQUENTIALLY.

PS: actually we have some "astute" guys here who could figure out the real reason.

Originally posted by sylvia weller:
Thanks for your example Rob. I believe you are
right but something still baffles me.
Wouldn't it be correct that becuase this room is
'synchronized' only one person can be in it any
time, and person2 must wait until person1 leaves
before coming in to use the marker? So there'd
be no grabbing possible, and no coffee breaks.
Each person has enter the room, draw a square,
draw a triangle,and leave, in that order.
How could a person leave the room before both
shapes are completely drawn?
Sorry to beat this to death, but what am I not
understanding? Thank you.
Sylvia

 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,
i still don believe that output should be sequential. its not guaranteed. i'm sure about that. try to run 10 other kind of threads (applications) along with (so the system load gets varied) and test the same code again and again for many times on different system with different memory and CPU capabilities
well, u may 've sequential output sometimes 'coz the for loop in run() is so small compared to the CPU speed and threads sometimes REALLY GETS late in calling run() method after the start() due to system load so by the time other thread really gets into run() the first one finished the process.
and one more thing,
Rob is right in saying that there is nothing wrong in S.o.p's implementation. because if u r famaliar with C programming u would have know that all "printf()" are BUFFERED. so, it's a dreadful job to get things printed right in order while having PROCESSES in C. i've experienced it. because sometimes some process gets blocked somehow and ur print stmt which u wrote before starting that process never gets on to the screen and u never know where the hell code didn't work!!
same thing happens here. when we have multiple threads waiting to print on screen we can't always determine the order.
I WOULD DEFINITELY GO FOR 'UNCERTAIN OUTPUT' as an answer.
again, threads are system dependent. thats why ur code should NEVER be designed to be affected by any kind of ordering or scheduling issue of threads to get right output. otherwise on one system it will work and in another u can't just predict as OS has lot of other work to do sometimes than just to run our java program.
But, yeah as Rob suggested if u do synch on S.o.p() then one can expect sequential output but here that is because of synchronized S.o.p() stmt and not the synch run() method at all.
And about Sylvia 's question that whether room is a synch object or pen...
doesnt matter. 'coz system can't deny any request to print. right? so if it blocks calling of print() or it blocks the printing operation after the print() call doesnt matter. if u had room synch then the other person would not enter till the first one finishes. if u had synch pen then other person would not write on the board till the first finishes. but the result is the same - THE BOARD IS NOT WRITTEN BY TWO PERSONS SIMULTANEOUSLY. if there were things a person would have been able to do in the room after entering then it will be a valid point to say that the room lock and pen lock are different

regards
maulin.
 
Ranch Hand
Posts: 281
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Rob Ross:

By synchronizing on the critical resource (System.out) you ensure that only one thread at a time can write to it completely before another thread starts writing to it as well.
Rob


I think in Michael Ernest's cert book (and forgive me if I'm wrong here Michael I don't have the book here at work and it may have been another author) he mentions that your better off synchronizing methods vs synchronizing objects. (I don't remember the reason why however).
Would it work if we synhronized a static method in the TestThread class like this:

or would that not also work? Just curious what the advantages/disadvantages are over synchronzing code blocks vs methods.
In one of my classes I created a singleton that acts to do all the database connection stuff with JDBC. In there I've played around with synchronizing the PreparedStatement blocks and also have tried it with synchronizing the method call that uses that PreparedStatement. Is there a benefit to doing it one way over the other?
Thanks for all the help.
Rick
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by mark stone:
sylvia: you are correct where the confusion is.
BUT in the cert exam what should we answer ?
plain situation:
run is synchronized and it prints out say 5 numbers sequentially.
and say three threads have to run this run method.
what do the sun guys expect us to answer ?
PS: actually we have some "astute" guys here who could figure out the real reason.


This astute guy has already told you what the answer is!
In the original example, TWO thread are created, each with a seperate instance of a Test object. The two threads can run independently of each other, and they do not use the same object, therefore there are no synchronization issues. But they are sharing one PrintWriter instance, namely System.out. So when each thread merrily goes along printing things to s.o, there is no guarantees which order each thread will issue println calls. So the output is UNDETERMINED AT RUNTIME!
Astute Rob
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rick,
it depends what you are trying to accomplish. You should synchronize the critical sections of your code that require atomicity, whether they are at the method level, or at the object level. Sometimes synchronizing at the method level is not the right approach, sometimes it is.

Rob
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I am sure that the original example would have the same output if run was not synchronized. The run() method is in two seperate objects, so each thread will get its class monitor locked. The place to look at really is System.out - which origianlly was not synchronized.
I am convinced that the correct answer should be: Cannot be determined.
-Bernd
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic