1

I'm implementing some sort of chat application and I need some help. This is the simplified code:

//...
Boolean stop = false;

while(!stop) {

    ServerRequest message = (ServerRequest) ois.readObject();
    broadcastMessage((String)message.getData()); //this method sends the client's message to all the other clients on the server

    stop = (System.nanoTime() - start >= handUpTime); // I want to let the client send his messages for no more than handUpTime seconds
} //...

I want to let a client to send his messages to the server for a certain amount of time (handUpTime) and then "block" him, but I don't know how to do this in an "elegant" manner. Of course, my code stumbles upon the ois.readObject() part, as the System waits to receive a message, and continues to run for more than handUpTime seconds. How can I solve this problem? I'm open to other approaches too.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
madalici98
  • 33
  • 3

1 Answers1

1

You can try:

ExecutorService executorService = Executors.newSingleThreadExecutor();

Callable<Object> callable = () -> {
    // Perform some blocking computation
    return someObject
};

Future<Object> future = executorService.submit(callable);

Object result = future.get(YOUR_TIMEOUT, TimeUnit.SECONDS);

If the future.get() doesn't return in certain amount of time, it throws a TimeoutException so you should handle the exception. See this post.

dim
  • 992
  • 11
  • 26