EsotericSoftware / kryonet

TCP/UDP client/server library for Java, based on Kryo
BSD 3-Clause "New" or "Revised" License
1.81k stars 415 forks source link

server.update(int timeout) returning after incorrect timeout. #164

Open ent-moot opened 3 years ago

ent-moot commented 3 years ago

There's a "bug" whereby the server.update() method might take longer to return than specified.

E.g. a call of server.update(10) may take 25ms to return.

This issue is caused because of the way in which a workaround has been implemented for an issue with NIO.

The fix is very straight-forward:

Replace this code, in Server.java:

// NIO freaks and returns immediately with 0 sometimes, so try to keep from hogging the CPU. long elapsedTime = System.currentTimeMillis() - startTime; try { if (elapsedTime < 25) Thread.sleep(25 - elapsedTime); } catch (InterruptedException ex) { }

with :

// NIO freaks and returns immediately with 0 sometimes, so try to keep from hogging the CPU. long elapsedTime = System.currentTimeMillis() - startTime; try { int targetDuration = Math.min(timeout,25); if (elapsedTime < targetDuration) Thread.sleep(targetDuration - elapsedTime); } catch (InterruptedException ex) { }

This ensures that, even if NIO "freaks out", we:

  1. Still avoid hogging the CPU
  2. BUT also avoid sleeping longer than the specified timeout

I have built and tested this locally, and it works, but not sure how to go about submitting it.