I have a method in which I call another method that has a callback. I want to receive this callback before leaving my method. I saw some other posts in which latches are used. My code looks like this:
public void requestSecurityToken(<some params>){
final CountDownLatch latch = new CountDownLatch(1);
MyFunction.execute(<someParams>, new RequestListener<Login>() {
#Override
public void onRequestFailure(SpiceException spiceException) {
//TODO
}
#Override
public void onRequestSuccess(Login login) {
//handle some other stuff
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This doesn't work, the method is stuck in the await() function. What happens is that, the method immediately jumps to the await(), and doesn't go into the onRequestSuccess() or onRequestFailure() method again. I guess this is a concurency problem... Any ideas on how to fix this issue?
EDIT: Added the line of code where I create the latch.
When you are doing this
new RequestListener<Login>
You are passing an object to your function , which implements an interface.
That is why those methods are not getting called , those methods are called only when you get the request result (success or failure).
You can do this instead.
MyFunction.execute(<someParams>, new RequestListener<Login>() {
#Override
public void onRequestFailure(SpiceException spiceException) {
someFunction();
}
#Override
public void onRequestSuccess(Login login) {
//handle some other stuff
someFunction();
latch.countDown();
}
});
public void someFunction()[
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Related
I need to run two processes simultaneously.
I wrote the code:
public void starttwoprocessing () {
final Thread tworunprocessing = new Thread(new Runnable() {
public void run() {
FlashLight.onFlashResume();
handler.post(new Runnable() {
public void run() {
camera.takePicture(null, null, photoCallback);
}
});
}
});
tworunprocessing.start();
}
First start:
camera.takePicture(null, null, photoCallback);
The second:
FlashLight.onFlashResume();
After changing places with the same result.
In this case, I get the first shot and the flash is started later.
Thread.sleep(...); does not help
How to start simultaneously flash, and immediately take a picture?
Thanks
written like this:
public class Launcher
{
public void main(String args[]) throws IOException, InterruptedException
{
try {
Process[] proc = new Process[2];
proc[0] = new ProcessBuilder("FlashPreview.onFlashResumeStart()").start();
Thread.sleep(3000);
proc[1] = new ProcessBuilder("camera.takePicture(null, null, photoCallback)").start();
try {
Thread.sleep(3000);
}
catch (InterruptedException ex)
{
}
proc[0].destroy();
Thread.sleep(3000);
proc[1].destroy();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Called:
mk = new Launcher();
try {
mk.main(null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Something I'm doing wrong.
Does not work at all, no crash, but wrote in the log:07-05 16:38:58.217: W/System.err(30934): java.io.IOException: Error running exec(). Command: [FlashPreview.onFlashResumeStart()] Working Directory: null Environment: [ANDROID_SOCKET_zygote=9, SECONDARY_STORAGE=/storage/extSdCard:/storage/UsbDriveA:/storage/UsbDriveB:/storage/UsbDriveC:/storage/UsbDriveD:/storage/UsbDriveE:/storage/UsbDriveF, ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/storage/sdcard0, ANDROID_ASSETS=/system/app, PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, ASEC_MOUNTPOINT=/mnt/asec, LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/framework2.jar:/system/framework/framework_ext.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar:/system/framework/sec_edm.jar:/system/framework/seccamera.jar, ANDROID_DATA=/data, LD_LIBRARY_PATH=/vendor/lib:/system/lib, ANDROID_ROOT=/system, ANDROID_PROPERTY_WORKSPACE=8,66560, VIBE_PIPE_PATH=/dev/pipes]
even using Threads your processes will runs after eche other. Using Threads means that second process no need to wait while first one is done. But easiest way how to fire two processes at the same time it is use timeout or ProcessBuilder
Also it can be good idea to run second process in first one. As for me it the best solution.
P.S. privet, ne chasto yvidiw zdes svoih s ykrainu)))
I have implemented the following:
class MyTask extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
FlashLight.onFlashResume();
}
#Override
protected Integer doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
camera.takePicture(null, null, photoCallback);
}
}
I have done something like this in my code
public void doWork()
{
Job job = new Job("Job")
{
#Override
protected IStatus run(IProgressMonitor monitor) {
while (rsMemName.next()) {
Display.getDefault().syncExec(new Runnable() {
#Override
public void run() {
try {
String memId = rsMemName.getString("id");
if (doMemberTasks(memId)==false)
{
cnn.rollback();
return;
}
} catch (Exception ex) {
ex.printStackTrace();
try {
cnn.rollback();
return;
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
}
}
job.schedule();
}
What i want to do is exit from the whole method if doMemberTasks(memId) returns false.
But it doesn't return from the method and keep looping on ResultSet. how can i terminate the thread from the run method?
Please give any suggestions how could i achieve that.....
Thanks in advance....
This is because return will return only from the thread run method. What you can do is set a variable(flag) probably static, and check its value after the run code to put another return statement.
Yeah your best bet would be to have a flag,
boolean doWork = true;
...
while( doWork && rsMemName.next(){
...
if (doMemberTasks(memId)==false)
{
cnn.rollback();
doWork = false;
return;
}
...
Thread showWordThread = new Thread() {
public void run() {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
this.run();
}
};
showWordThread.run();
}
...
It had run for about 5 minutes before error occured:
Exception in thread "Thread-2" java.lang.StackOverflowError.
Why?
I had tried this:
Thread showWordThread = new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
But error still occured.
Others have explained that you should use a while loop instead. You're also trying to call the run method inside your anonymous class declaration. Additionally, you should call start, rather than run - when the new thread has started, it will call run automatically. I'd actually suggest implementing Runnable rather than extending Thread, too. So you want:
Thread showWordThread = new Thread(new Runnable() {
#Override public void run() {
while (someCondition) {
try {
Thread.sleep(config.delayTime * 1000);
// Presumably do something useful here...
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
Alternatively, consider using a Timer or ScheduledExecutorService.
You are calling run method as recursively. Java holds call information(such as parameters) in stack memory so when you are calling a method recursively and there isn't any end point, stack memory will consumed and StackOverflow exception throws.
Maybe you want increasing Heap Size of JVM but this solution don't solve your problem and StackOverflow will occurred .
I guess you want run a thread continually. I recommend following code:
Thread showWordThread = new Thread()
{
public void run()
{
try
{
sleep(config.delayTime * 1000);
}
catch (Exception e)
{
System.out.println(e.toString());
}
// this.run(); this snnipet code make error
}
};
showWordThread.run();
}
Don't call run() from within the run() method. That'll definitely produce a stack overflow because you keep reentering the same method with no exit condition. Instead use a while loop.
Thread showWordThread = new Thread() {
public void run() {
while(condition) {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
};
showWordThread.start();
}
Your code have infinity recursive, you should change the code to:
Thread showWordThread = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
};
showWordThread.start();
Your function calls itself each time you run it.
That results in a stack overflow.
Maybe because you call run method (this.run()) from itself?
I have a java code like this:
private class Uploader implements Runnable
{
// ...
public void start()
{
t.start();
}
public void run()
{
try {
while(i=in.read())
{
output.write(i); // THIS IS A BLOCKING CALL !!
}
} catch(ProtocolException e) { ... }
catch(IOException e1) { ... }
}
private void restore()
{
...
}
private class Checker implements Runnable
{
// ...
#Override
public void run()
{
// I WANT (IN A PARTICULAR MOMENT) TO THROW AN
// EXCEPTION INTO THE Uploader RUN METHOD FROM HERE,
// IS IT POSSIBLE?
}
}
}
The problem is that i have a blocking write() in the Run() method, so I have added a
new thread that checks whether or not the connection is transmitting: if it's not trasmitting I want to stop the blocking write() using the exception mechanism (throwing an exception to the other thread's run() method from the checker thread).
Is it possible?
EDIT [SOLVED]:
The only way is to brutally close the output stream and to work on the amount of written bits to check whether the connection is transmitting:
private class Uploader implements Runnable
{
private OutputStream output;
private int readedBits;
public void run()
{
try {
while(i=in.read())
{
output.write(i);
readedBits++;
}
} catch(IOException e1)
{
// ENTERS HERE IF RESTORE() IS CALLED
}
}
private void restore()
{
try {
output.close();
} catch (IOException e) {}
// Restore connection ....
}
private int getReadedBits()
{
return this.readedBits;
}
private class Checker implements Runnable
{
// ...
#Override
public void run()
{
while(true)
{
try {
Thread.sleep(timeout);
} catch (InterruptedException e1) {}
if(lastReaded >= getReadedBits())
restore();
else
lastReaded = getReadedBits();
}
}
}
}
You can make your code honor Thread.interrupt() call. See javadoc of this call.
Not exactly what you've asked for but I'd rather use java.nio and
public abstract int select(long timeout) throws IOException
to (not only) detect timeouts.
In general with blocking on I/O the only way to move on is to close the resource. As #VolkerK says, the other approach is to use non-blocking I/O, which is more difficult.
I recommend using Interrupts for this. Checker may call interrupt on Uploader class.
E.g.
private class Checker implements Runnable
{
// ...
Uploader uploader;
public Checker(Uploader uploader) {
this.uploader = uploader;
}
#Override
public void run()
{
// CHECK
if(failed) uploader.interrupt();
}
}
Documentation is here: http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
I'm trying to implement a piece of code to synchronously start looped service in Java. The idea is, code under // STARTER comment should be considered as piece of Service.go() method, so if service fails to start, I want to re-throw the exception synchronously. That piece of code should only finish in case I've tried to start the thread, waited until its execution flow reached some point and next, if there are no problems, my go() method quits and thread goes on, or, if there were problems, I can re-throw the exception caught in thread's run() method from my go() method. Here's the solution that seems to work fine, but I'm curious if it's possible to make it a couple times shorter :-)
public class Program {
private static boolean started;
private static Throwable throwable;
public static void main(String[] args) {
final Object startedSetterLock = new Object();
Thread thread = new Thread() {
public void run() {
System.out.printf("trying to start...\n");
boolean ok;
Throwable t = null;
try {
init();
ok = true;
} catch(Exception e) {
ok = false;
t = e;
}
synchronized(startedSetterLock) {
started = ok;
throwable = t;
startedSetterLock.notifyAll();
}
if(!ok) {
return;
}
while(true) {
try {
System.out.printf("working...\n");
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.printf("interrupted\n");
}
}
}
private void init() throws Exception { throw new Exception(); } // may throw
};
// STARTER
synchronized(startedSetterLock) {
thread.start();
try {
startedSetterLock.wait();
} catch(InterruptedException e) {
System.out.printf("interrupted\n");
}
}
// here I'm 100% sure that service has either started or failed to start
System.out.printf("service started: %b\n", started);
if(!started) {
throwable.printStackTrace();
}
}
}
And also, there's a reason to have initialization code executed within that thread, so, please, don't advise running initialization code explicitly in go() method and then just passing all the stuff to the thread.
Thanks!
How about overriding the Thread.start() method?
public static void main(String[] args) {
Thread t = new Thread() {
public void run() {
while (true) {
try {
System.out.printf("working...\n");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.printf("interrupted\n");
}
}
}
#Override
public synchronized void start() {
try {
init();
} catch (Exception e) {
throw new RuntimeException(e);
}
super.start();
}
private void init() throws Exception {
throw new Exception("test");
}
};
t.start();
}