how do I synchronize a code-section? semaphores?

I know how to use the synchronized methods, but how do I synchronize code-sections inside mehods?

For instance, if I have a vector in a class that must never be tampered with by two threads at the same time but i don't feel like making synchronized wrapper-methods around the methods in the Vector class. This is easily done with semaphores, but there are no semaphores in java (why the heck not, by the way?).

Someone told me it's possible to use a statement involving synchronize, is this the case?

Any ideas are very much appreciated!

/Mattias

[586 byte] By [matper-8] at [2007-9-26 3:13:50]
# 1

This requires a little more creative use of the synchronized keyword.

private void doCrititalOp() {

Vector v = getCriticalVector();

synchronized( v ) {

// do critical stuff

}

}

Since most of the methods on Vector are synchronized, nobody else will be able to use the Vector while you are in this code. You don't even has to modify the Vector in the code, in which case the Vector basically becomes just the semaphore you are looking for. But there is no reason you cannot do whatever you like with the Vector.

ShagVT at 2007-6-29 11:23:30 > top of Java-index,Core,Core APIs...
# 2

A couple of things to note:

1) Vector's methods are already synchronized, so if you just don't want one method call on the Vector interfering with another, it's already taken care of for you.

2) If you need to sync across larger operations--for example {add, add, sort, delete}, with the ops listed in braces being "atomic" then you could do like ShagVT suggested, with my "{}" ops being his "// do critical".

However, you need to be careful here. Every piece of code that could potentially interfere with this--every piece that has to respect that atomicity--must also sync on the same Vector.

private void veryRudeOp() {

Vector v = getSameCriticalVectorAsOtherCode();

// do rude stuff to v without synchronizing

}

Here, another thread can come in, and since it's not syncing on the critical vector, it can run willy nilly all over the middle of what's supposed to be an atomic op. The key point is that "synchronized" doesn't "prevent any other thread from accessing the object" (as some people mistakenly believe); rather, it prevents any other thread from obtaining the same object's lock (until the sync block exits or calls wait() )

jverd at 2007-6-29 11:23:30 > top of Java-index,Core,Core APIs...