Hello everyone, I got a question on synchronization, hope someone will be able to give me a clear explanation.

public void sendToAll( String message ) {
 
.....
    synchronized( outputStreams ) {
 ...
 
    ""statement block""

 
    
    }
}

outputStreams is an object here. I made some research and I found that its a synchronize statement .


And that the object specified in the statement is the lock. Could you please explain to me what really happens in the piece of code.

Its for a chat system, I am implementing multi threading in my chat.

This is supposed to send the "message" to all the ouputstreams(to all clients).

The object outputstreams is a list of all the output stream for all clients which have connect to the server.


But I want to know how the message is send, in parallel ? one by one ?? what is the function of lock ? Hope to get an answer soon.

Thanks in advance.

So, if you've got two threads executing at the same time, and they both try to use the same object (such as an OutputStream) at the same time, you can get "unexpected" or "unpredictable" results (aka absolute chaos).
The synchronised (...) { ...} syntax mens that the current thread tries to get a lock on the object. Once it's got the lock it will go on to execute the code in the {} and when that's finished it releases the lock.
If a second thread tries to do the same thing while the first thread still has the lock, the second thread will be held up and will wait in the synchronised statement until the first thread releases the lock. Once the lock is released, the second thread will be able to lock the object and continue its execution.
This means that all the threads that want to use the object will have to wait in turn, and only one of them will ever bea able to access it at one time, thus making the program "thread safe"

Okie .. thanks a lot.

I got it. So ... only one thread will be able to use the object at one time. Thats it?

Thanks a lot James. Btw, I got one last question on my thread "Constructors and Threads".

So ... only one thread will be able to use the object at one time. Thats it?

Yes, as far as the code in the synchronised { code } block is concerned

Btw, I got one last question on my thread "Constructors and Threads".

What's that? I can't see it!

Sorry ... I just posted the question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.