How can I get some value in inner class in java? - java

I want to return some value depend on some value in inner class:
public boolean rename(File file) {
new OnResultListener() {
#Override
public void onResult(AsyncResult<CharSequence> result) {
// some codes
// Here is what I want to do
if (succeed) {
// rename return true
} else {
// rename return false
}
}
}
}

You can't and it does not make sense. These are two distinct functions that may very well be called on different threads. What you have to do, if you insist on returning something, is that the "rename" function itself should receive a callback as a parameter that gets called upon success. That is, if the downstream call is asynchronous then the ones calling it should be too.

An alternative would be to have a the calling function ("rename" in this case assuming it calls the function that notifies the OnResultListener) to wait on some mutex. Then, in the nested method upon receiving a result, you set some flag and then call notify() which would wake the thread held by the wait.

Related

Eventually load member variable value in a non blocking thread safe manner

I have a class that has a getter method (among others):
public class Employee {
public EmployeeAccount getAccount() {
return this.empAccount;
}
}
The problem is that the empAccount is initialized by an async call which might return null but eventually would return the actual account.
The reason is that the async call method depends on many things and sometimes might return null as it is not ready to give the account yet. Please note that I have no control over this API.
So I was thinking of doing something like:
public class Employee {
public EmployeeAccount getAccount() {
if(this.empAccount != null) {
retrieveAccount();
}
return this.empAccount;
}
private void retrieveAccount() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
this.empAccount = getAccountFromRemoteSystem(); // <--- this is a blocking call
}
};
t.start();
}
The reason I was aiming towards this is because getAccount() is expected to be non-blocking as it is called from a UI thread.
How can I design/structure my code so that it is thread safe? Are there better constructs I can use or some other design pattern?
The answer begets a specification question. Do you specify that an instance of the Employee class is usable even if that instance's EmployeeAccount (you should perhaps rename it to Account) is not yet available?
It appears that it is a valid Employee instance if the account is not yet set up. In that case, it is important to state that in the contract of the getAccount method:
/** Returns the {#linkplain EmployeeAccount} with this instance.
It may be null, if the account is not yet set up at the time of
this call. Typically, the clients should retry if this method
returns null.
#return EmployeeAccount if it is available, null otherwise.
*/
public EmployeeAccount getAccount() {
//
}
Deferring the construction of account to a later time runs the risk of the account never getting assigned a valid, non-null value for a valid looking Employee reference. This is why there's nothing like final fields and immutable instances.
If this caveat is something you and your clients are okay with, then I'd go ahead with what you have above. Make sure that the employee field is either volatile or AtomicReference, so that the updates made to it by the background thread that retrieves the real account from a remote/async call are visible to the other threads (e.g. the UI thread that calls the getter).

persisting information through multiple recursive calls

I am extending a 3rd party class and overriding a method that I have made "recursive" like so:
public class SubFoo extends Foo {
....
#Override
public void bar(...) {
recursiveSpecificSet.add(...);
if(recursiveSpecificSet.contains(...)){
...
methodCallThatCallsBar(...);
...
}
}
}
Since this method is overrided, I have no control in the method signature. I would like to pass information from the parent recursive call to its child through the recursiveSpecificSet, but I would like that information to be specific to that recursive chain. For instance:
SubFoo sf = new SubFoo();
sf.methodCallThatCallsBar(...); // first call calls bar recursively 3 times
sf.methodCallThatCallsBar(...); // second call calls bar recursively 5 times
In the above code, the first call's recursiveSpecificSet variable should not interfere with the second call's recursiveSpecificSet.
Is this even possible? I know you can usually pass info between recursive iterations through method parameters, but I do not have control on the method signature. Multiple calls to the bar method can also occur in the same thread, so a thread local variable will not work.
Use a threadlocal that stores recursion depth and the payload data. If upon entering bar() the threadlocal is null, initialize it with depth 1, otherwise increment depth. Upon leaving bar(), decrement depth and if it goes under 1, delete the threadlocal. You'll probably have to do this in finally so it doesn't break in case of an exception being thrown.
public void bar() {
if (threadLocal == null) {
threadLocal.set(new Context(recursiveSpecificSet));
}
threadLocal.get().increaseDepth();
try {
...
methodCallThatCallsBar(...);
...
}
finally {
threadLocal.get().decreaseDepth();
if (threadLocal.get().isExitRecursion()) {
threadLocal.remove();
}
}
}
If I understand your question correctly, the answer is not to make bar recursive, but to make bar call a private helper method that is recursive.
#Override
public void bar() {
helper(new HashSet<>());
}
private void helper(Set<String> recursiveSpecificSet) {
...
helper(recursiveSpecificSet);
...
}

Singleton with a Listener versus Join

I inherited this code from a previous developer (lol). I'm considering changing this to support a join instead of using a listener kind of callback.
My requirements:
1. I need to have the calling thread wait until the DoMath class thread has completed.
2. I need to prevent other threads from calling it.
This, in another thread (and class) - :
DoMath.getInstance().performMathCalc();
It doesn't wait or sleep of course when it calls this:
public class DoMath {
protected math calc() {
}
public static DoMath getInstance() {
if(_instance == null) {
_instance = new DoMath();
}
return _instance;
}
// perform a synchronous math calc, and return a boolean indicating success or failure.
public boolean performMathCalc() {
MathEngine.setApplicationMode(MathEngine.AUTO);
MathEngine.getInstance().StartMathCalc(MathEngine.DIVISION);
return true;
}
// perform an async math calc, and call back the listener when done
public void performMathCalc(final listener client) {
Thread mathThread = new Thread(new Runnable() {
public void run() {
boolean result = performMathCalc();
client.mathFinished(result);
}
});
mathThread.setDaemon(true);
mathThread.start();
}
public static interface listener {
public void mathFinished(boolean success);
}
protected static DoMath _instance;
}
So, is it better to just use the listener or implement a join in the calling class?
Do note that this:
public static DoMath getInstance() {
if(_instance == null) {
_instance = new DoMath();
}
return _instance;
}
is not thread-safe. To ensure that your class really is a Singleton (relative to its ClassLoader) you must either synchronize that method or initialize the _instance member in its declaration. Either way, _instance must be private or final or both.
As for your actual requirements,
(1) it seems you want to either change an asynchronous call into a synchronous one, or to put a synchronous wrapper around it. You can do the latter via the existing listener interface, which would preserve the ability to perform asynchronous jobs. If you don't want that then instead of joining, skip launching a new thread at all: just run the computation in the current thread.
(2) How you might prevent multiple threads from running calculations at the same time depends in part on how you address issue (1). If you make everything synchronous then you can just make DoMath.performMathCalc() a synchronized method. If you retain the asynchronous computation option then you could look to package java.util.concurrent.locks for classes that can help you.
Do you really want to pause your thread until the other one as finished? You should never, ever block the main thread.
The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,
t.join();
causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.
(from java docs)
Also, does performMatchCalc() needs to be public ?
Now, at first glance that code actually looks correct, but, you can still prevent someone from starting another calculation. Perhaps with something similar of this :
public class DoMath {
private Thread mathThread;
protected math calc() {
}
public static DoMath getInstance() {
if(_instance == null) {
_instance = new DoMath();
}
return _instance;
}
// perform a synchronous math calc, and return a boolean indicating success or failure.
public boolean performMathCalc() {
if(null != mathThread && mathThread.isAlive())
return false;
MathEngine.setApplicationMode(MathEngine.AUTO);
MathEngine.getInstance().StartMathCalc(MathEngine.DIVISION);
return true;
}
// perform an async math calc, and call back the listener when done
public void performMathCalc(final listener client) {
//re-start calculation? if so
if(null != mathThread && mathThread.isAlive()) {
matchThread.interrupt();
matchThread = null;
}
mathThread = new Thread(new Runnable() {
public void run() {
boolean result = performMathCalc();
client.mathFinished(result);
}
});
mathThread.setDaemon(true);
mathThread.start();
}
public static interface listener {
public void mathFinished(boolean success);
}
protected static DoMath _instance;
}
I need to have the calling thread wait until the DoMath class thread has completed.
You already have this. Note how there are two performMathCalc methods:
The first method takes no arguments and performs the calculation on the caller thread, then returns the result. This fulfills your first requirement.
The second method is an asynchronous wrapper for the first; it allows the caller to kick off a calculation, then go off an do something else with the understanding that, at some point in the future, someone will be notified that the operation has completed. This is useful functionality, so I would keep it.
I do see one issue with the asynchronous wrapper, however: the listener will not be notified in the event that the core performMathCalc() method throws an exception. Consider using a try/catch/finally block to ensure the listener always gets notified, even if an error occurs. You'll need to decide whether to add a second callback to your listener (e.g., mathFailed) or to simply call mathFinished(false) on errors.
I need to prevent other threads from calling it.
We can accomplish this easily enough, and since the asynchronous version simply delegates to the synchronous version, we only need to lock down the synchronous version. The simplest way would be to mark the method as synchronized, since your class only provides one logical function:
public synchronized boolean performMathCalc() {
MathEngine.setApplicationMode(MathEngine.AUTO);
MathEngine.getInstance().StartMathCalc(MathEngine.DIVISION);
return true;
}
Alternatively, if you end up extending your DoMath class to perform other kinds of operations that are not mutually exclusive, you can synchronize on operation-specific locks.
That leaves us with your singleton accessor:
public static DoMath getInstance() {
if (_instance == null) {
_instance = new DoMath();
}
return _instance;
}
This conditional initialization is not thread-safe. Your singleton is very simple and doesn't have any up-front initialization costs, so simply mark _instance as final static and initialize it in the declaration.

How to make a thread return arraylist of objects in java?

I want a thread to return list. I cant use the run method as its return type is void. I am using the thread in a separate private method inside a class under which the caller method of the thread is also there. The caller needs the list from thread result to do some manipulation. here is my thread. Pls help me in understanding how can i return list from this thread.
private List<myObject> fetchmyObjList(final String abc){
new Thread(new Runnable() {
#Override
public void run() {
try {
List<myObject> myObjList = anotherInternalMethod(abc);
} catch (Exception e) {
System.out.println(e);
}
}
}).start();
}
how can i make this thread return myObjList to the caller?? Please help.
You need Callable instead of Runnable.
Here is an how-to-use callable: https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6
Use callable instead of Runnable. The function is capable of returning a value in the form of Futures. You can utilize this to achieve your own purpose.
You can push your data to external object (like object which have fetchmyObjList) using just a method like:
List<myObject> myObjList = anotherInternalMethod(abc);
setFetchedObjects(myObjList);
This is a scenerio when you puts controll to newly created thread. We can call it simplivied observer pattern - outer object is notified by method call when data is available. But remember about thread safety in this scenerio!
Other scenerio is to use Callable<OBJECT YOU WANT TO RETURN> and use a Thread/ExecutorService to start your task. Then (in control in your outer object) you can use Callable .get() to get your result.
You cen use blocking or nonblocking methods to wait for result or to check if result is ready to receive from background task.
Of course in your scenerio, creating a Thread with Callable just to block original thread and wait to task completion to return your objects from method, gives nothing - it would be better to not use threads at all.
If you want to perform background operation, change your method signature to return null + call a "listener" method when data will be ready or return a Callable<List<myObject>> and retreive data from it after some other operations done in pararell.
You need to rethink what you're doing. The new thread will run in parallel with the old one, and may not have an answer ready until the calling thread's got a lot more work done. You could make the calling thread wait, but why not just call 'anotherInternalMethod' from the main thread?
You could do something like this (but don't!):
private void fetchmyObjList(final String abc, final List<myObject>[] retList) {
new Thread(new Runnable() {
#Override
public void run() {
try {
retList = anotherInternalMethod(abc);
} catch (Exception e) {
System.out.println(e);
}
}
}).start();
}
but the passed retList object (a one-element array) will not get set correctly until some unpredictable time in the future.
This can be solved by the Callable interface in place of Runnable, and retrieving the value with a Future object, which also lets you wait until the value has been computed. You can achieve this with an ExecutorService.

When to use synchronized in Java

I hope this is going to be enough information, so here it goes. If you need more info, lemme know in the comments.
I have a class that has two inner classes. The inner classes each have two methods that call a method in the outer class. So, it looks like this:
public OuterClass {
private boolean outerMethodHasBeenCalled = false;
private void outerMethod() {
if(!outerMethodHasBeenCalled) {
// do stuff
}
outerMethodHasBeenCalled = true;
}
private FirstInnerClass {
public void someMethod() {
outerMethod();
}
}
private SecondInnerClass {
public void someOtherMethod() {
outerMethod();
}
}
}
It's important to note that:
This is for an Android app. Instances of FirstInnerClass and SecondInnerClass are passed to a WebView as a JavaScript interface, so someMethod and someOtherMethod can be called at any time, in no particular order.
I currently have a problem with the existing code (without the synchronized keyword) where outerMethod is called pretty much at the exact same time (I print out a log message, and they're timestamped to the 1000th of a second) by different objects. My app then 'does stuff' twice because outerMethodHasBeenCalled is still false when outerMethod was called. This is not okay, and it is exactly what I'm trying to prevent. My app should only 'do stuff' once and only once: the first time outerMethod is called.
It might sound like I have multiple instances of OuterClass, but rest assured that it's only one instance of OuterClass.
It's important that my app 'does stuff' only the first time outerMethod gets called (I hope that's evident by now). All subsequent calls are essentially ignored. Whichever inner class calls outerMethod first -- doesn't matter.
So, is it appropriate to use the synchronized keyword in this case?
Yup, given what you've laid out above, I'd go with:
private synchronized void outerMethod() {
...
}
Note, this will have the side-effect of blocking one of the callers until the outerMethod() completes. If that is acceptable, cool. If the intent is merely that the code in outerMethod() is run once, and it is OK for the second caller not to be delayed if the first caller is running outerMethod(), you might consider:
public OuterClass {
private AtomicBoolean outerMethodHasBeenCalled = new AtomicBoolean();
private void outerMethod() {
if (outerMethodHasBeenCalled.compareAndSet(false, true)) {
// do stuff
}
}
...
See the JavaDoc for AtomicBoolean to grok what is going on there (assuming it is available in Android's Java).
Wrap everything in outerMethod that you want to run only once in a synchronized block:
private void outerMethod() {
synchronized (this) {
if(!outerMethodHasBeenCalled) {
// do stuff
}
outerMethodHasBeenCalled = true;
}
}
That way, the first time the method is called, only one thread will be allowed into the synchronized block at a time. The first one will execute the code in the if statement, then set outerMethodHasBeenCalled to true. The other threads will see that it is true, and skip the if code.

Categories