Inconsistent number of Observers on two different method calls to Observable - java

I'm trying to use observable in my code and there is this problem giving me hard time.
public class observeState extends Observable
{
public void setSelectedTransaction(int idx)
{
if (selectedTransaction != idx)
{
this.selectedTransaction = idx;
setChanged();
notifyObservers("setSelectedTransaction");
System.out.println("Observers : "+this.countObservers());
}
}
public void setLog(Log log)
{
if(theLog != log) {
theLog = log;
System.out.println(theLog.getLogTransactions().size() + "setLog");
setChanged();
notifyObservers("setLog");
System.out.println("Observers : "+this.countObservers());
}
}
There are two observers observing this observable class and it does send out notifyObservers when the setSelectedTransaction method is called with the test line "Observers : 2". However the next method setLog does not seem to have observers giving "Observers : 0". I don't think I can only use observable method once.

The mostly likely cause of this issue is that you are not calling the method on the same object. It is a common mistake to assume two objects are the same because they have the same name or some other confusion. I would print out the hashCode of each object or use a debugger to ensure you really are calling the same object.
BTW you can try making the calls in the opposite order, or more than once
to test your theory.

Either the objects that you are using to call the setSelectedTransaction and setLog are different or the observers might be removing themselves as observers in the update method.

Related

unsafe.compareAndSwapObject replacing an array that is being iterated in another thread

I am trying to implement logic that will allow me to update an array in one thread using sun's unsafe.compareAndSwapObject utility while safely iterating over that same array, in a different thread. I believe that the CopyOnWriteArrayList does what I am searching for however it uses locking for the updating and I am trying to develop a solution that does not have any locks.
The compare and swap logic is as follows:
public void add(final Object toAdd) {
Object[] currentObjects;
Object[] newObjects;
do {
currentObjects = this.objects;
newObjects = ArrayUtil.add(currentObjects, toAdd);
} while (!UNSAFE.compareAndSwapObject(this, OBJECTS_OFFSET, currentObjects, newObjects));
}
While the iteration logic is as follows (the toString() is a placeholder):
public void doWork() {
Object[] currentObjects = this.objects;
for (final Object object : currentObjects) {
object.toString();
}
}
My questions are:
Is this code safe?
Does this give me the same snapshot behaviour that CopyOnWriteArrayList does?
If it does, when is the iteration snapshot formed?
Does the fact that I'm creating a local variable have anything to do this?
If it does, how does the JVM know to not optimise this away?
Have I essentially created a variable on the stack that has a reference to the most up to date array object?
Lastly to follow up the third point above about "snapshot" creation, would the following code work the same way:
public void doWork() {
actuallyDoWork(this.objects);
}
public void actuallyDoWork() {
for (final Object object : currentObjects) {
object.toString();
}
}

how to convert asynchronous promise code to rxjava

I have the following synchronous code that I would like to model as async code in RXJava.
void executeActions(List<Action> action) {
if (action == null || action.size() == 0) return;
for (Action action: actions) {
executeActions(action.handle());
}
}
class Action {
//implementation of handle
// return List<Action> or null.
List<Action> handle() {
}
}
Now in JS I can model this interaction with Promises like so. (Pseudo code below - my JS is weak)
executeActionsAsync(actions) {
var p = Promise.resolve();
action.forEach(function(action) {
p = p.then(function() {
action.handle();
})
}
return p;
}
class Action() {
function handle() {
actions = [];// some array of actions.
executeAsync(actions);
}
}
I would like to model the same in RXJava2. Any help is appreciated.
First of all, Sorry for my bad English.
I edited entire answer because I did not catch what his question is.
I don't know how implement of your Action class's handle function, However this function return value should change to RxJava2's async classes. In this case, Maybe class.
You wants how to implements recursion of async.
Handle List or null.
Use Maybe if you want to handle something or null. in RxJava2
class Action {
Maybe<List<Action>> handle() {}
}
This is what your Action class's handle returns.
void executeActions(Maybe<List<Action>> rxactions) {
// add null check.
// List<Action> handles as stream, but you can use for or iterator or whatever you want.
rxactions.subscribe(actions -> actions.stream().map(action -> executeActions(action.handle())));
}
Important thing is, handle() function returns properly.
Additional
In RxJava2, There are multiple classes to handle async.
Single, Flowable, Observable, Completable. And each classes instance method, subscribe.
Simply say,
1.Single => returns single class.
2.Flowable, Observable => returns multiple classes. (Flowable is more complex than Observable, which added back pressure.)
3.Completable => returns nothing, just succeed or not.
4.Maybe is returns * or null.
5.subscribe is execute this async.
:: Each classes can convert easily.
:: And There are so many ways to solve one problem. so it is just reference.
ex) Single<List<Foo>> <=> Flowable<Foo> // This is not same. but treat as similar.
PS.
I had this experience too. I think you need to learn more about RxJava2 to use properly everywhere.
Promise can devide into Single, Flowable, Observable, Completable. As describe above. This is the KEY to start understanding RxJava2.

Is it possible to return from a method using #Advice.OnMethodEnter?

Using Byte Buddy's advice API, is it possible to return from the instrumented method without actually executing it?
One use case would be to implement a cache and to return the cached value, if present, instead of computing the value again.
#Advice.OnMethodEnter
public static Object returnCachedValue(#Advice.Argument(0) String query) {
if (cache.containsKey(query)) {
// should "abort" method call
return cache.get(query);
}
}
I know that this code sample above just creates a local variable which I can get in a #Advice.OnMethodExit method. But is there a way to abort the method call on an explicit return? If yes, is this also possible for void methods?
No, this is not possible, a return value can only be set from exit advice. But it can be emulated by skipping the original method in case that a value already exists and by setting this value from the exit advice in case that the enter advice defines a value:
class MyAdvice {
#Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class)
public static Object returnCachedValue(#Advice.Argument(0) String query) {
if (cache.containsKey(query)) {
return cache.get(query);
} else {
return null;
}
}
#Advice.OnMethodExit
public static void processCachedValue(
#Advice.Return(readOnly = false, typing = DYNAMIC) Object returned,
#Advice.Enter Object enter) {
if (enter != null) {
returned = enter;
} else {
cache.put(query, returned);
}
}
}
Of course, this does not work if the cached value is null. To avoid this, you could wrap the value in some instance to make sure that the enter value is never null. Doing so would also allow to use the above pattern to void methods.
This might look inconvenient to program but the idea of advice is that Byte Buddy can use the advice class as a template and inline the byte code without much work to avoid a runtime overhead.

How does this asynchronous call work in my example

I learn Java and wonder if the item in this code line:
useResult(result, item);
Will be overrwritten by the next call coming from the
doItem(item);
Here´s the eaxmple:
public void doSomeStuff() {
// List with 100 items
for (Item item : list) {
doItem(item);
}
}
private void doItem(final Item item) {
someAsyncCall(item, new SomeCallback() {
#Override
public void onSuccess(final Result result) {
useResult(result, item);
}
});
}
the SomeCallback() happens some time in the future and it´s another thread
I mean will the useResult(result, item); item be the same when callback return?
Please advice what happens here?
I mean will the useResult(result, item); item be the same when callback return?
Of course it will, what would the utility of that be otherwise?
What you are doing is creating 100 different SomeCallback classes, that will process a different Item object.
A skeleton for your someAsyncCall may look like this:
public static void someAsyncCall(Item i, Callback callback) {
CompletableFuture.runAsync( () -> { // new thread
Result result = computeResult(i);
callback.onSuccess(result, i);
});
}
The point is: Callback, at the moment of instantiation, doesn't know anything about the Item he will get as parameter. He will only know it, when Callback::onSuccess is executed in the future.
So, will Item i change (be assigned a new object) ?
No, because it is effectively final within someAsyncCall (the object value is not explicitly changed).
You can't even assign i = new Item(), as the compiler will complain about the anonymous function accessing a non-final variable.
You could of course create a new Item and pass it to the callback
Item i2 = new Item();
callback.onSuccess(result, i2);
but then it would become one hell of a nasty library...
Nobody forbids you to do i.setText("bla") though, unless your Result class is immutable (the member fields are final themselves).
EDIT
If your questions is how java handles object in method parameters, then the answer is: yes, they are a just copy of the original instances.
You could try with a simple swap method void swap(Item i1, Item 12); and you'll notice the references are effectively swapped only within function, but as soon as you return the objects will point respectively to their original instances.
But it's a copy that reflects the original instance.
Coming back to your example. Imagine your someAsyncCall waits 10000 ms before executing the callback.
in your for loop, after you call doItem, you also do: item.setText("bla");.
When you print item.getName() within useResult you will get bla. Even though the text was changed after the async function was called.

Index Service Design - Sync / Async

I have a requirement to index items. This service should run Sync or Async.
I started designing an Interface
public interface IndexService{
public void index();
}
And two implementation, one for a Async Index:
public class AsyncIndex implements IndexService {
public void index(){
//... Creates a Thread and index the items
}
}
And the other one to the Sync Index
public class SyncIndex implements IndexService {
public void index(){
//... Creates a Thread and index the items
}
}
But now there is another design that is having a IndexService, who has a flag to execute as a async service or as a sync service:
public interface IndexService{
public void index(int mode);
}
So now the implementation will know how to run base on that flag.
I know that the first design is better, but I need pros and cons to explain why.
I go for first approach because
1- code is cleaner AsyncInex class only has codes related to async call and syncIndex would has its own code.
2- you can avoid else if
...
public void runService(IndexService service) {
service.index()
}
// some where in your code
runService(new AsyncIndex());
// or
runService(new SyncIndex());
as you are working with interface "IndexService" you can always change implementation without changing clients code.
specially if you are using DI frameworks you can have the kick of it ;).
this is so important to not allowing client code know about the implementation. suppose situation where you are indexing, for instance, a database.
you want to do async index when data is huge or sync index when data is small.
caller should has no knowledge about the way Index is called. this way you can have different strategy in different situations without changing callers code. if you take the second approach you have to do some extra work.
I say both.
Assume, you plan to use the second approach. Your implmentation may look like:
public SyncOrAsyncIndex implements IndexService {
public void index(int mode) {
if(mode == 0) {
//sync processing code
} else if (mode == 1) {
//async procesisng code
}
}
That said, are you going to write all the implementation within this index method or SyncOrAsyncIndex class. That will possibly end up being unmanageable.
So, the index method may end up like this:
public void index(int mode) {
if(mode == 0) {
new SyncIndex().index(); //for example
} else if (mode == ) {
new AsyncIndex().index(); //for example
}
}
Assume, you decide on supporting a third mode. Imagine the plight of the index method or SyncOrAsyncIndex class. So, the first approach is needed.
So, as per "code to the interface" strategy the first approach is suggested. If the invoker is aware of the type of indexing, they can just instantiate the particular type and use it.
Else, along with the first approach the second one may be required as a factory or strategy to calculate which type of indexing to use based on the passed parameter. The invoker would then use the SyncIndex or AsyncIndex via SyncOrAsyncIndex.

Categories

Resources