If you have an observer with an “infinite loop”, it is no longer an observer pattern.
You can start a different thread for each observer, but observers MUST NOT be prohibited from changing the state of the observed object.
The simplest (and most stupid) method is to simply take your example and make it threaded.
void notify() { for (observer: observers) { new Thread(){ public static void run() { observer.update(this); } }.start(); } }
(this has been manually encoded, unverified and probably has a mistake or five - and this is a bad idea)
The problem is that this will make your machine short, as it must allocate several new threads at once.
So, to fix the problem with all the initial steps, use ThreadPoolExecutor because it will A) process threads, and B) may limit the maximum number of threads that can be executed.
This is not determinate in your "Loop forever" case, since each forever loop will constantly have one of the threads from your pool.
It’s best not to let them loop forever, or, if they should, create their own flow.
If you need to maintain classes that cannot be changed, but you can determine what will run fast and which will run “Forever” (in computer terms, which, it seems to me, are more than second or second), you CAN use such a cycle:
void notify() { for (observer: observers) { if(willUpdateQuickly(observer)) observer.update(this); else new Thread(){ public static void run() { observer.update(this); } }.start(); } }
Hey, if it really is “Loops Forever”, will it consume a stream for each notification? It looks like you might have to spend more time on your design.