I am trying to do a bit of asynchronous programming, but my Java skills are a bit rusty…
Here’s my code:
private static String uname="xxx";
private static String pword="xxx";
private static int productId=82;
private static String sessionToken="";
public static void main(String[] args)
{
BFGlobalService_Service service=new BFGlobalService_Service();
BFGlobalService betfair=service.getBFGlobalService();
System.out.println("hello");
LoginReq loginReq=new LoginReq();
loginReq.setUsername(uname);
loginReq.setPassword(pword);
loginReq.setProductId(productId);
loginReq.setLocationId(0);
loginReq.setVendorSoftwareId(0);
LoginResp loginResp=new LoginResp();
loginResp=betfair.login(loginReq); //this line is very slow ;(
sessionToken=loginResp.getHeader().getSessionToken();
...
}
The line “loginResp=betfair.login(loginReq)” takes time (I have a very slow 3G network) and holds up the whole program flow. Can I raise an event when this completes?
i.e. I’d like this kind of event handler pseudocode:
private void handleNewLoginResp(...)
{
System.out.println("login response received");
sessionToken=loginResp.getHeader().getSessionToken();
}
I’m hoping this will be straightforward enough! I’ve tried googling, but all I can find is articles on GUIs, etc.enter code here
Read up on Java Concurrency. Assuming you have a UI, you’ll want to use SwingWorker, or whatever is functional equivalent for your environment.
Update:
The only part that might trip you up is that a listener will be called on the background thread’s context, not the main thread’s. So, you will need to use synchronize blocks to ensure objects created on the background thread are flushed from the thread’s cache to common memory.
It’s no different than writing custom event handling for the GUI. (Which is why you’re not finding anything when you search.)