Can you use "synchronized" for data members

N

Nagrik

Hello Group,

Can the "synchronized" kew word be used in front of data members. I
am aware that it can be used in fron of methods, and a block.
Something like this.

public class myclass {

synchronized prinvate int counter; // Is it allowed

}

If the answer is yes then in what situation it is adviseable.

Thanks in advance..

nagrik
 
T

Tom Anderson

No. Use "volatile" for that.

Yes. Although it isn't *quite* the same thing.

By which i mean that:

class Smeagol {
private volatile int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}

And:

class Deagol {
private int x;
public synchronized int getX() {
return x;
}
public synchronized void setX(int x) {
this.x = x;
}
}

Have slightly different semantics. If thread A calls getX, and then thread
B calls setX, then with Deagol, there is a happens-before relationship
between the two calls. With Smeagol, there is not. Whereas if A calls setX
and then B calls getX, both Smeagol and Deagol will generate a
happens-before relationship.

Or so i believe. I hope someone will correct me if i'm wrong.

The good news is that in most cases, the weaker guarantees provided by
Smeagol's volatile are actually just what you want (because you don't care
that a write to a variable happens after a read), and the JVM can generate
a more streamlined sequence of instructions for it.

tom
 
J

Joshua Maurice

No.  Use "volatile" for that.

Oh goodness no. He's trying to make a simple int counter. Volatile
won't give atomic incrementing. He needs to have a synchronized block,
something like:
synchronized (someObject) {
++counter;
}
(Or something else fancier from the concurrent packages maybe (?) if
you're super concerned about speed and measurement says it helps.)

As a precaution, note that it will not work if you change counter to
Integer and synchronize on that, because Integers are immutable which
means different threads will be synchronizing on different objects
which doesn't give you the guarantees you need.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top