• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

synchronized methods + Threads

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



1. i.v guaranteed always to be 0 or 1
2. j.v guaranteed always to be 0 or 1
3. k.v guaranteed always to be 0 or 1
4. j.v will always be greater than or equal to k.v at any given time.
5. k.v will always be greater than or equal to j.v at any given time.
 
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I guess the answer should be both 1 and 2.
Whats the correct answer?
 
Parameswaran Thangavel
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi
can any please explain me
 
author
Posts: 23959
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Parameswaran Thangavel:
hi
can any please explain me



Let's look at the possible answers...

1. i.v guaranteed always to be 0 or 1
2. j.v guaranteed always to be 0 or 1
3. k.v guaranteed always to be 0 or 1
4. j.v will always be greater than or equal to k.v at any given time.
5. k.v will always be greater than or equal to j.v at any given time.

As for the methods, a() and b() are both synchronized. They can't be ran in parallel via different threads. The c() method is not synchronized, it can be ran in parallel, even while a() or b() is running.

(3) is not true as you can have two c() method running in parallel, and having increment the count before decrementing the count -- producing a value of 2. (albeit very short lived)

(4) is not true as a ramification of (3). K can have large values... In theory, hard to produce in practice.

(5) is not true based on how method b() works. It increments j before incrementing k... hence, j is larger than k for the really small period between the two methods.

Now that leaves (1) and (2) which is only modified from a() and b(), and which can only run via a single thread, and always runs in pairs, inc() followed by a dec().

Henry
 
reply
    Bookmark Topic Watch Topic
  • New Topic