• 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

K&B scjp5 Exercise 9.2 - Synchronizing a block of Code (Chapter 9: Thread)

 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello there,

I have tried this exercise. Following are my codes. It runs and produces desired output.
But I'm not sure whether I did it in a correct way. Please let me know if there's anything that I should correct.



Thanks

_charles


NB. Let me know if you need to see the exercise 9.2 question.
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Let me know if you need to see the exercise 9.2 question.


That's right, not everyone has the K&B book at hand, so it would be better if you post the question here, that will increase chances of a good reply...
 
Charles Chikito
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here it goes...

Exercise 9-2

In this exercise we will attempt to synchronize a block of code. Within that block of
code we will get the lock on an object, so that other threads cannot modify it while
the block of code is executing. We will be creating three threads that will all attempt
to manipulate the same object. Each thread will output a single letter 100 times, and
then increment that letter by one. The object we will be using is StringBuffer.
We could synchronize on a String object, but strings cannot be modified once
they are created, so we would not be able to increment the letter without generating
a new String object. The final output should have 100 As, 100 Bs, and 100 Cs all in
unbroken lines.

1. Create a class and extend the Thread class.
2. Override the run() method of Thread. This is where the synchronized
block of code will go.
3. For our three thread objects to share the same object, we will need to create
a constructor that accepts a StringBuffer object in the argument.
4. The synchronized block of code will obtain a lock on the StringBuffer
object from step 3.
5. Within the block, output the StringBuffer 100 times and then increment
the letter in the StringBuffer. You can check Chapter 5 for StringBuffer
methods that will help with this.
6. Finally, in the main() method, create a single StringBuffer object using the
letter A, then create three instances of our class and start all three of them.
 
Ankit Garg
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your code is correct, no need to change anything...
 
Charles Chikito
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks

_charles
 
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hey i would like to ask the difference between synchronized(s) and synchronized(this);
 
Bartender
Posts: 4116
72
Mac TypeScript Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ankur kothari wrote:hey i would like to ask the difference between synchronized(s) and synchronized(this);


First one synchronizes on the object refered by "s" while the latter synchronizes on the current(i.e: this) instance.
 
Ankur kothari
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i get the output of AAA...BBB...CCC.... when i use synchronize(s) but the output is different when i use "this"......what exactly happens when i used "this"....i thought the output should be the same
 
Vijitha Kumara
Bartender
Posts: 4116
72
Mac TypeScript Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ankur kothari wrote:i get the output of AAA...BBB...CCC.... when i use synchronize(s) but the output is different when i use "this"......what exactly happens when i used "this"....i thought the output should be the same


In the first case you are synchronizing on s (which is shared by all three threads), so once aquired the lock that thread will finish then others will have a chance to aquire the lock, hence you get that output. But with synchronizing on "this" there's no such gurantee as those threads synchronizing on those different "MyThread" instances. So any thread can be executing in a given moment.
 
Ankur kothari
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
but whenever a new thread is started isnt the value of s going to be A since everytime a new thread is created the Stringbuffer is initialised to A......
please explain....
 
Vijitha Kumara
Bartender
Posts: 4116
72
Mac TypeScript Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ankur kothari wrote:but whenever a new thread is started isnt the value of s going to be A since everytime a new thread is created the Stringbuffer is initialised to A......
please explain....


All three threads initialized with the same StringBuffer which has the value "A". When one thread finishes looping it sets the value of "sb" to something else, so next execution (whichever thread it is) will print that new value as all those threads share the same StringBuffer object.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ankur kothari wrote:but whenever a new thread is started isnt the value of s going to be A since everytime a new thread is created the Stringbuffer is initialised to A......
please explain....



No, the StringBuffer is initialised only once, before any MyThreads are made, to "A". The only initialisation that goes on inside MyThread is to point the "s" reference to the same StringBuffer object - crucially, the contents of the StringBuffer are not reset within the constructor. Once the first thread has changed the contents of the StringBuffer to "B" (remember, all s'es point to the same object on the heap, it's only the reference "s" that is copied for each thread and not the object itself), the second thread gets (a copy of) the same reference and continues printing what is now a StringBuffer with "B" in it. And so on.

Edit: ah, you beat me to it, Vijitha. Oh well, two answers is better than none I guess
 
Ankur kothari
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hey i get the desired output if instead of extending thread i implements runnable


here i am creating just a single instance and thus when i synchronize(this) i am actually doing it on a single instance thus everytime a new thread starts it starts with the old value of S.............so the output

but when i extends Thread i create multiple objects to start multiple threads and thus synchronized(this) cant be used as there are many instances.......

correct me if i was wrong so far..........

but what i don't understand is using synchronized(s)....isnt the value of s "A" everytime a new thread starts......so why am i getting the output of A.......100timesB.......100timesC.....100times
 
Ankur kothari
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks vijita and Vevang.....understood everything...i replaced StringBuffer with String and output comes is all A.....
 
Vijitha Kumara
Bartender
Posts: 4116
72
Mac TypeScript Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ankur kothari wrote:Thanks vijita and Vevang.....understood everything...i replaced StringBuffer with String and output comes is all A.....


If you want to print only "A" then remove the part which sets the value of StringBuffer you'll get all "A"s.
 
Oyvind Vevang
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ankur kothari wrote:but what i don't understand is using synchronized(s)....isnt the value of s "A" everytime a new thread starts......so why am i getting the output of A.......100timesB.......100timesC.....100times



Whether you synchronize on s or on this (in your case), each thread has to wait for the lock to be released. Even if the value of s is "A" when start is called on all three threads, only the first one to get the lock gets to actually run and print any A's. (The other threads are waiting for the lock.) Then it modifies the StringBuffer and releases the lock, and one of the remaining threads acquires the lock and enters the synchronized block. The final thread has to wait until both the other threads are done, and by this time s has been modified to "C".
 
I just had the craziest dream. This tiny ad was in it.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic