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);
loginRe开发者_高级运维q.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.)
If there is not a non-blocking version of the login()
function available, you should run it in a separate thread, and fire off an event when it's done.
Beware though, working with multiple threads means that you have to consider concurrency issues.
You will need to look up things like thread-safety, the java synchronized
keyword and Listeners.
(Listeners (or Event Listeners) are non-essential, but they're the design concept you'll need to make a well engineered solution.)
精彩评论