Need help with callbacks and anonymous classes in Java

I use some third-party library to connect to the server via the asynchronous protocol and receive a response. For example, a method for obtaining a username from a username is as follows:

public int getUserid(String username) { int userid = 0; connection.call("getUserid", new Responder() { public void onResult(final int result) { System.out.println("userid: " + result); //how to assign received value to userid and return it? } }, username); //wait for response while (userid == 0) { try{ Thread.sleep(100); } catch (Exception e) {} } return userid; } 

The problem is that I cannot assign the returned “result” from the server’s response to the variable “userid” from the method (to return it after). How to solve this? I can probably assign it to some class variable, not a method variable, but I want to keep it within the scope of the method, so I don't need to deal with concurrency issues.

Thanks.

+6
java scope callback anonymous-class
source share
2 answers

If I understand your question correctly, you ask how you can write a variable from an anonymous class.

Anonymous classes can only access finite variables and cannot directly "write" them.

A simple solution that is “good enough” is to create a ValueBox class with one value field and a receiver and an installer. Then you can create a new instance of the function as a final variable and access your anonymous class. An anonymous class will use its getter and setter for writing / reading.

The fact that the variable is final means that you cannot direct the link elsewhere, but you can still change the contents of the mentioned object from any function.

The big problem you are facing is waiting for a callback call. This kind of wait-sleep may be good enough, but you might think about timeouts, threads, etc., depending on what you are trying to achieve.

Moreover, all of this assumes that you will never call it twice in a mix. Otherwise, you need to provide us with additional information about your synchronization model.

Here is a sample code:

 public int getUserid(String username) { final ValueBox<Integer> userid = new ValueBox<Integer>(); connection.call("getUserid", new Responder() { public void onResult(final int result) { System.out.println("userid: " + result); userId.setValue(result); //how to assign received value to userid and return it? } }, username); //wait for response while (userid.isEmpty()) { try{ Thread.sleep(100); } catch (Exception e) {} } return userid.getValue(); } 
+2
source share

The simplest change is to use something like java.util.concurrent.SynchronousQueue . But perhaps you yourself want to provide an event driven interface.

0
source share

All Articles