• 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

Doubt on Synchronisation

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a question from Mughal Khalid's mock scjp test applet:

Given the following code, which statements concerning the objects referenced through the member variables i, j and k are true, given that any thread may call the methods a(), b() and c() at any time?

class Counter {
int v = 0;
synchronized void inc() { v++; }
synchronized void dec() { v--; }
}
public class Q7ed5 {
Counter i;
Counter j;
Counter k;
public synchronized void a() {
i.inc();
System.out.println("a");
i.dec();
}
public synchronized void b() {
i.inc(); j.inc(); k.inc();
System.out.println("b");
i.dec(); j.dec(); k.dec();
}
public void c() {
k.inc();
System.out.println("c");
k.dec();
}
}
Options as answers were
1)i.v is guaranteed to be 0 or 1.
2)j.v is guaranteed to be 0 or 1.
3)k.v is guaranteed 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.
Answer given was 1 and 2.

I could not figure out how would k.v not be 0 or 1.And is it possible to figure out options 4 and 5.
Please help.
 
Ranch Hand
Posts: 405
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I will give it try and explain my thinking on why I agree that the answers should be 1 and 2.

Methods a() and b() are synchronized and method c() is not. Method a() only updates "i.v", while method b() updates "i.v", "j.v", and "k.v", but keep in mind that the un-synchronized method c() updates "k.v" also.

While access to "i.v" and "j.v" is synchronized any thread can update "k.v" through method c(). So the only thing you can be sure about is the


I hope my explanation did not confuse you more. I hope this helps.
 
reply
    Bookmark Topic Watch Topic
  • New Topic