1

Is it possible to synchronize a variable such that all references to that variable are implicitly assumed to be synchronized? I'm thinking something like the following:

synchronized List l = new LinkedList(); // I know this isn't valid

l.add(4)
l.set(0, new Integer(5));
// add a bunch of things
l.get((int) (Math.random()*l.size()));

would be compiled as

List l = new LinkedList();

synchronized(l){
  l.add(4)
}
Integer temp = new Integer(5);
synchronized(l){
  l.set(0, temp);
}
// add a bunch of things
double temp2 = Math.random();
synchronized(l){
  int temp3 = l.size()
}
int temp4 = (int) temp3;
synchronized(l){
  l.get(temp4);
}

EDIT This is just an example using List. I'm looking for a general way to do this for any object I might create.

ewok
  • 20,148
  • 51
  • 149
  • 254

2 Answers2

3

No you can't.

There are some classes like AtomicInteger, that may help you. Read more about Atomic classes here: Practical uses for AtomicInteger.

In some situations you can use the volatile keyword for primitives like int.

Community
  • 1
  • 1
AlexWien
  • 28,470
  • 6
  • 53
  • 83
1

No you cannot and no you should not.

The first question to ask is, which lock would you get? You'd either need to lock on the object or keep an external cache of all locks for all objects.

The first method would cause thousand of deadlocks. What if the object is already thread safe and already lock on itself? Monitors are non-reentrant, which means that a thread trying to lock the same object twice would deadlock.

The second method would work, however, when do you release the memory of those locks? You will endup with a huge cache for all locks for all objects (even those that the GC reclaimed). This cache would only grow, and it would eventually take all your memory.

Aspect-oriented programmation can solve this type of issue. However it requires a third party library and byte-code rewrites.

Jazzwave06
  • 1,883
  • 1
  • 11
  • 19