Hector Hector - 5 months ago 32
Java Question

Retrofit REST client for Android and Java does not terminate

I am investigating the Retrofit REST client for Android and Java.

Using a standard Java project within Eclipse I am using @POST with void return type.

Making Asynchronous calls.

Everything works as expected, however my test main method never terminates. I have to manually stop each test execution.

What do I need to do (or stop doing) so that my tests terminate automatically?

Here's my java code.

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class Android {

private static final RestAdapter mRestAdapter =
new RestAdapter.Builder()
.setEndpoint("http://localhost:8080/resources/registrations")
.build();

public static void main(final String... args) {

final AndroidRegister androidRegister =
mRestAdapter.create(AndroidRegister.class);

Callback<Void> callback = manufactureCallback();

androidRegister.androidRegisterInterface(
new RegistrationIdJson("1111-2222-3333-4444"), callback);
}

private static Callback<Void> manufactureCallback() {
return new Callback<Void>() {

@Override
public void failure(final RetrofitError retrofitError) {
System.out.println("retrofitError-->"
+ retrofitError.getLocalizedMessage() + "<---");
}

@Override
public void success(final Void returning,
final Response response) {
System.out.println("-->" + returning + "<--->"
+ response.getStatus() + "<---");
}
};
}
}

Answer

By default, Retrofit uses a non-daemon thread pool with a 60s core pool timeout. Very, very rarely do you want to use Retrofit's async Callback behavior in this manner.

If you are simply testing, you can call setExecutors on the RestAdapter.Builder and pass a synchronous executor as the first argument and null for the second. This will allow you to use the asynchronous API but get synchronous behavior in your tests.

And a synchronous executor, if you don't know how to make one:

public final class SynchronousExecutor implements Executor {
  @Override public void execute(Runnable r) {
    r.run();
  }
}
Comments