Java and event driven programming

zengr picture zengr · Feb 8, 2011 · Viewed 10.6k times · Source

I am using javaeventing to write an even driven shell to access a database. So, my use case is:

  1. open up the shell in command line.
  2. Now, the shell connects to database and listens for the command coming in.
  3. when it gets a command, it executes it and gives back the required output.

Now, how can I avoid while(!exit){ //do stuff } kind of loop here? How to use Java eventing correctly?

The straight forward way can be:

while(!exit)
{
   exit = myClass.execute("command"); //when command is exit, return true.
}

But, I am looking if java eventing can give a better solution.

Update1:

Here is what I am trying to implement:

1 My application is a shell (like mongodb shell) to try out a key-value database.
2 The simple code:

init(); //Initialize the connection with database
while(!exit)
{  
    //exit = myClass.execute("put(5)"); //This returns false  
    exit = myClass.execute("exit"); //returns true, i.e. the user wants to exit the shell
}

Now, here I do not see the use of java eventing and I solved my problem, can you please tell me, HOW java eventing will come in picture here? I want the user to trigger the event.

Answer

Will Hartung picture Will Hartung · Feb 8, 2011

All that eventing library does is dispatch events to listeners. Beyond that you need something to actually CREATE the events.

In this case, you would need code to read the console and generate events, you would need potentially something else to "listen" to the DB and generate events from that (assuming you have asynchronous DB events you're looking for, such as table or row changes).

That code still needs to be written.

And unless that framework provides to you such utility classes, you'll have to write that yourself, and those classes will likely be just like you describe.

But those classes are all at the edge of the system, driving the data. The rest of your code can all be completely event based.