Can I write somethings like a Notification in Java? - java

In Objective-C I use a Notification to do some tasks, which required some time to process. I can listen to the Notification, until it is ready...
For example:
[[NSNotificationCenter defaultCenter] addObserver:objectB
selector:#selector(objectReceived:)
name:#"objectATasks"
object:nil];
[objectA doALongProcess];
When the objectA is finished the task, the #"objectATasks" will be fired, and the objectB's objectReceived: will be called. Do have have similar things / concept in java? Thank

You can make use of the Observer design pattern in java

Seems that you are using the observer pattern, of course you can implement it also in Java, take a look here .

The closest to that in "stock" Java is a Future, but that doesn't let you add continuations. You may want to use the ListenableFuture interface in Guava with its addListener method. Then you can use MoreExecutors to create a ListeningExecutorService - you submit tasks to that, which gives back a ListenableFuture.
(The point of using this instead of rolling your own implementation of the Observer pattern is that it's already done for you in a way which is specifically designed for this sort of use case, reacting to a task being completed - rather than the various other kinds of observer implementations which may be reacting to just properties changing etc, without considering thread safety. Why design your own API when smart people have already done it for you?)

Related

What is the equivalent of C++'s Futures in Java

I was looking for an asynchronous way of setting a variable and notify the possible listeners that the variable is now available.
C++ has a great API for this use case called std::future (wait and set_value).
But the Future's of Java are completely different...
Is there an alternative API in Java that accomplished the same behavior like in C++?
Credit goes to #JornVernee for providing an answer in the comments
You are looking for CompletableFuture:
A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.

Is SerializedSubject necessary for thread-safety in RxJava

I created a Subject instance in RxJava and call its onNext() from multiple threads:
PublishSubject<String> subject = PublishSubject.create();
//...
subject.onNext("A"); //thread A
subject.onNext("B"); //thread B
The RxJava documentation says that:
take care not to call its onNext( ) method (or its other on methods) from multiple threads, as this could lead to non-serialized calls, which violates the Observable contract and creates an ambiguity in the resulting Subject.
Do I have to call toSerialized() on such Subject assuming I don't care if "A" goes before or after "B"? How would serialization help?
Is Subject thread-safe anyway or will I break RxJava without toSerialized()?
What is the "Observable contract" that the documentation mentions?
Do I have to call toSerialized() on such Subject assuming I don't care if "A" goes before or after "B"?
Yep use toSerialized() because all operators applied to the subject assume that proper serialization is occurring upstream. The stream may fail or produce unexpected results if this does not happen.
Is Subject thread-safe anyway or will I break RxJava without toSerialized()?
answered above
What is the "Observable contract" that the documentation mentions?
Rx Design Guidelines.pdf section 4 defines the Observable contract:
4.2. Assume observer instances are called in a serialized fashion
As Rx uses a push model and .NET supports multithreading, it is possible for different messages to arrive different execution contexts at the same time. If consumers of observable sequences would have to deal with this in every place, their code would need to perform a lot of housekeeping to avoid common concurrency problems. Code written in this fashion would be harder to maintain and potentially suffer from performance issues.
I think RxJava documentation should make this more discoverable so I'll raise an issue.
According to Dave's answer, if you know beforehand that your Subject is going to be accessed from different threads, you could wrap it into a SerializedSubject
http://reactivex.io/RxJava/javadoc/rx/subjects/SerializedSubject.html
Wraps a Subject so that it is safe to call its various on methods from different threads.
like:
private final Subject<Object, Object> bus = new SerializedSubject<Object, Object>(PublishSubject.create());
(taken from Ben Christensen's EventBus example here: http://bl.ocks.org/benjchristensen/04eef9ca0851f3a5d7bf )

Name for pattern in which actions happen upon completion of a future event / Java class

I have a class currently called Promise that works as follows:
It holds a future value
It can always accept a subsequent action to take that uses the future value as the parameter
When the value is completed the function queue launches
Any functions added after the future is complete happen synchronously
So this seems to be a design pattern from functional programming that we're jamming into Java. The important thing is that we can daisy-chain on delayed events, which I understand is a feature more built into C# 3.0 language but you have to hack together with Java classes. Unfortunately, one, I don't know a better name for this than "promise" or "future," which seem misleading since the focus is more on the "DelayedCallStack" then the value at hand, and two, I don't know of any way to do this beyond writing our own fairly complicated Promise class. Ideally I'd like to lift this from the functional Java library but the concept eludes me thus far.
Note Java doesn't even give language/library support for an asynchronous callback that takes a parameter, which is one reason I'm so pessimistic about being able to find this.
So, what is this pattern, can it be done in libraries?
Take a look a ListenableFuture in Guava:
http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
ListenableFuture allows you to add callbacks to be executed when the Future computation is completed. You can control what thread pool the callbacks get executed under, so they can be executed synchronously or asynchronously.
I can only say that we implemented pretty much exactly the same thing in Flex (ActionScript) and we also called it a Promise. In Clojure a promise is something quite a bit more lightweight: the get operation on it blocks until another thread delivers the promise. It's basically a one-element queue except that it retains its value forever, so subsequent gets always succeed.
What you have is a kind of a promise coupled with observers of its value. I'm not aware of any special term covering exactly that case.
EDIT
Now I notice that your "promise/future" might own the code that produces its future value (at least it's not entirely obvious whether it does). The ActionScript implementation I mentioned didn't do that -- it behaved like Clojure's, the value being supplied from the outside. I think this is the key distinction between a future and a promise.

Observer: Implement with pattern (subject & observer) or inter-thread communication (wait & notify)

I usually use the Observer pattern, my colleague at work though has implemented an Observer using Thread intercommunication (using wait and notify/notifyAll).
Should I implement my observers using the pattern or inter-Thread-communication using wait and notify? Are there any good reasons to avoid one approach and always use the other?
I've always gone with the first one, using the pattern, out of convention, and because it seems more expressive (involved identifiers are a good way to express and understand what is communicated and how).
EDIT:
I'm using the pattern in a Swing GUI, he's using the inter-thread solution in an Android application.
In his solution one thread generates data and then calls notify, to wake up another thread that paints the generated data and calls wait after every paint.
His argument for the wait/notify solution is that it creates less threads and even several concurrent calls to notify will cause only 1 paint event, whereas an observer-based solution would call a repaint with every call. He says it's just another valid approach, but doesn't claim he's done it for performance reasons.
My argument is that I would express the communication among objects on the OO design level rather than use a language-specific feature that makes the communication almost invisible. Also, low-level thread communication is hard to master, might be hard to understand by other readers, and should rather be implemented on a higher level, i. e. using a CyclicBarrier. I don't have any sound arguments for one or the other solution, but I was wondering if there are any sound arguments for either one or the other approach (i. e. "This-and-that can happen, if you use this approach, whereas in the other one that's not possible.").
You are comparing apples and oranges. The wait/notify mechanism is used for thread synchronization, and while your colleague may have used it within an Observer/Observable implementation, it is not, in itself the pattern implementation. It simply means it is a multithreaded implementation.
There are many implementations of this pattern, and they are typically tailored to the environment in which you are working. There are event mechanisms built into most UI frameworks/toolkits. JMS for distributed environments, ...
I don't find much use for the generic Observer/Observable classes provided by the JDK, and from experience I haven't found many other developers use them either. Most will use a provided mechanism, if appropriate, or roll their own specific and ultimately more useful implementation if needed.
Since I have done most of my coding in an OSGi environment of late, I have a preference for a variation of observer/observable called the whiteboard pattern. This may or may not be feasible for you, depending on your environment.
You should avoid, or rather refrain from, inter-thread communication in 99.99% of the cases. If there is a real need for a multi threaded solution, you should use a higher level concurrency mechanism such as an ExecutorService or a good concurrency library such as jetlang: http://code.google.com/p/jetlang/.
Difficult. I would normally use Observer / Observable when not explicitly writing a multithreaded application. However, convention in this case might be for you to use his design. Perhaps see if you can abstract it out somehow so that you can replace it with the Observer pattern at a later stage if necessary?
However, I found these two articles which seem to indicate that the Observer/Observable pattern in Java is not ideal and should be avoided.
An inside view of Observer and
The event generator idiom

Android: looper/handler vs. Java Observer?

Aren't these competitors? I'm thinkin they're not, but don't see it.
How about within the context of an Activity needing to learn when a Service has new xyz?
Thanks!
They are for different purpose so you can't compare in the way that one exclude the other as perhaps you may intend. I explain:
Registered Observers receive notification of a change all together sequentially simply calling once notifyObservers(..).
Handlers allow you to modify UI components from a background thread but you handle/update only 1 "observer" (the one handled by the Handler).
More advanced, if you think, you can even combine the two, to always be exception free while update UI from a background thread still keeping the Observer pattern.
I think nobody answered you in these 5 years because almost nobody is aware of great power of Observer pattern ;-)

Categories

Resources