Re: Oldie Synchronize Question from Newbie
- From: Thomas Hawtin <usenet@xxxxxxxxxxxxxxxxx>
- Date: Sat, 27 Aug 2005 20:58:18 +0100
Russ wrote: > [...]
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?
It does not appear to be anything that requires synchronisation. Presumably msgBuffer is fixed. It doesn't access anything mutable that might be shared. Two threads passing through the method (or other blocks synchronised on the instance) at the same time will notice each other.
protected void sendRawMessage( Message msg ) throws IOException { synchronized( out ){ [...] } }
public void put( Message msg ){ synchronized( buffer ){ [...] } } [...] 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(); } }
Here be race conditions. Almost always, wait should be called from within a while loop. To synchronised blocks like that are a good sign of trouble.
for (;;) {
Message message;
synchronized (buffer) {
for (;;) {
if (Thread.currentThread() != runner) {
return;
}
if(!buffer.isEmpty()) {
break;
}
buffer.wait();
}
message = (Message)buffer.firstElement();
buffer.removeElementAt(0);
}
sendRawMessage(message);
}(Usual disclaimer.)
Now since "sendRawMessage" method is being called by two seperate threads ( diversion "msgBuffer" and original "sendMessage" ) shouldn't it be synchronized as well?
What are you trying to protect?
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?
In general you need to group together operations into a logical task. Your operations seem to do that on out and buffer.
Tom Hawtin -- Unemployed English Java programmer http://jroller.com/page/tackline/ .
- References:
- Oldie Synchronize Question from Newbie
- From: Russ
- Oldie Synchronize Question from Newbie
- Prev by Date: Oldie Synchronize Question from Newbie
- Next by Date: Bound property
- Previous by thread: Oldie Synchronize Question from Newbie
- Next by thread: Bound property
- Index(es):
Relevant Pages
|