Oldie Synchronize Question from Newbie



Hi All,
As a relative Java newcomer I have taken over -on an amateur level-
development of an applet that is forever stuck in Java 1 for
technical reasons, but still has uses in art and education :)
I preface my question with this fact, so folks understand why there
are some archaic appoaches used in the code examples.
My question is in regard to when a method needs to be "synchronized"
I did not write the following snippets of code and have some
reservations about them.

The following method can possibly be called by two or more different
threads at the same time:

public void sendMessage( Message msg ) throws IOException {
if( msg.getType() == ControlMessage.TYPE ){
sendRawMessage( msg );
}
else {
msgBuffer.put( msg );
}
}

By all rights then, shouldn't "sendMessage" be synchronized?

i.e.: public synchronized void sendMessage( Message msg ) ....

What makes the question tricky and creates reservations (in my mind
anyway)is that the method "sendRawMessage" has a synchronized
DataOutputStream ("out") and the "put" method of inner class
"msgBuffer" uses a synchronized Vector
class (I did say it was archaic!) as a buffer:

protected void sendRawMessage( Message msg ) throws IOException {
synchronized( out ){
out.writeInt( msg.getType());
msg.write(out);
out.flush();
}
}


public void put( Message msg ){
synchronized( buffer ){
if( !buffer.isEmpty()){
Enumeration list = buffer.elements();
RealTimeMessage rt, help;
rt = (RealTimeMessage) msg;
while( list.hasMoreElements()) {
help = (RealTimeMessage) list.nextElement();
if( help.tag.equals( rt.tag ) && help.data.getType() ==
rt.data.getType()){
buffer.removeElement( help );
break;
}
}
}
buffer.addElement( msg );
buffer.notify();
}
}

The "msgBuffer" inner class also has a thread that then
delivers the synchronized Vector's (buffer) contents back
to the method "sendRawMessage" after sorting :

public void run(){
Message msg;
while( Thread.currentThread() == runner ){
try{
if(!buffer.isEmpty()){
synchronized( buffer ){
msg =(Message) buffer.firstElement();
buffer.removeElementAt(0);
}
sendRawMessage( msg );
}
else {
synchronized( buffer ){
buffer.wait();
}
}
catches a bunch of exceptions .....

Now since "sendRawMessage" method is being called by two seperate
threads ( diversion "msgBuffer" and original "sendMessage" )
shouldn't it be synchronized as well?

Or am I simply off base here, because since both Vector and
DataOutputStream classes are synchronized the methods containing
them don't need to be?


Thanx
Russ Kinter

.