Scafuro: So i modify the code and now I launch a server-thread that takes 2 argument: the event I want to publish (this one of SPublish(event) method) and the list of Subscriber into the System.
As i suggested before, I think
you should have a queue of events here for the Servitore thread. The thread should poll this queue for events. Whenever, it gets the event it should dispatch it to the list of subscribers.
This is exactly what a ThreadPool provides you.
Executors provide you a way to create a fixed size threadpool. You can use this for the threads polling a queue infrastructure.
If you are prior to jdk 5, use the
backport of the concurrent utils.
Storing the event object inside the Servitore thread makes it bound to a single event i.e. you will have as many of these threads as the number of events. Thread creation is always an expensive process, so you must use a threadpool here.
Scafuro: If it doesn't works, as I think you said, could you propose a solution to this synchronisation problem?
I did not say it does not work. What I said was that it is not a good idea to expose the wait-notify mechanism to the subscribers. Your whole processing then depends on the subscriber. (What if a subscriber implementation forgets to send a notify?)
Instead you can modify the Subscriber dispatch method as follows:
In the above Callback is an interface that only has a done() method. The Servitore class can implement this interface to handle a completion of the event processing by the subscriber.
You can implement it using wait-notify or anything else. The subscriber never knows about it.
I dont think after this you will need any synchronize blocks in Subscriber.
Also, you can remove synchronization on Abbonati in the Servitore thread as Abbonati does not change.
BTW, It is better to implement Runnable than to extend Thread.
Read this for more info on this.