public long periodStringToMillis(String p) {
   Matcher m = periodPattern.matcher(p);
   String s;
   int num;
   String unit;
   long millis = 0;
   while (m.find()) {
     s = m.group();
     num = Integer.parseInt(s.substring(0, s.length() - 1), 10);
     unit = s.substring(s.length() - 1).toLowerCase();
     if (unit.equals("d")) {
       millis += TimeUnit.MILLISECONDS.convert(num, TimeUnit.DAYS);
     } else if (unit.equals("h")) {
       millis += TimeUnit.MILLISECONDS.convert(num, TimeUnit.HOURS);
     } else if (unit.equals("m")) {
       millis += TimeUnit.MILLISECONDS.convert(num, TimeUnit.MINUTES);
     } else if (unit.equals("s")) {
       millis += TimeUnit.MILLISECONDS.convert(num, TimeUnit.SECONDS);
     }
   }
   if (millis == 0) {
     millis = Long.MAX_VALUE;
   }
   return millis;
 }
  @Test
  public void testWaitForQuiescenceAfterRequestCompleted() throws IOException {
    mockServer
        .when(request().withMethod("GET").withPath("/quiescencecompleted"), Times.exactly(1))
        .respond(response().withStatusCode(200));

    try (CloseableHttpClient client = NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
      HttpResponse response =
          client.execute(
              new HttpGet("http://127.0.0.1:" + mockServerPort + "/quiescencecompleted"));
      EntityUtils.consumeQuietly(response.getEntity());

      assertEquals(
          "Expected successful response from server",
          200,
          response.getStatusLine().getStatusCode());
    }

    // wait for 2s of quiescence, now that the call has already completed
    long start = System.nanoTime();
    boolean waitSuccessful = proxy.waitForQuiescence(2, 5, TimeUnit.SECONDS);
    long finish = System.nanoTime();

    assertTrue("Expected to successfully wait for quiescence", waitSuccessful);

    assertTrue(
        "Expected to wait for quiescence for approximately 2s. Actual wait time was: "
            + TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS)
            + "ms",
        TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) >= 1500
            && TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) <= 2500);
  }
  @Test
  public void testWaitForQuiescenceQuietPeriodAlreadySatisfied()
      throws IOException, InterruptedException {
    mockServer
        .when(request().withMethod("GET").withPath("/quiescencesatisfied"), Times.exactly(1))
        .respond(response().withStatusCode(200));

    try (CloseableHttpClient client = NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
      HttpResponse response =
          client.execute(
              new HttpGet("http://127.0.0.1:" + mockServerPort + "/quiescencesatisfied"));
      EntityUtils.consumeQuietly(response.getEntity());

      assertEquals(
          "Expected successful response from server",
          200,
          response.getStatusLine().getStatusCode());
    }

    // wait for 2s, then wait for 1s of quiescence, which should already be satisfied
    Thread.sleep(2000);

    long start = System.nanoTime();
    boolean waitSuccessful = proxy.waitForQuiescence(1, 5, TimeUnit.SECONDS);
    long finish = System.nanoTime();

    assertTrue("Expected to successfully wait for quiescence", waitSuccessful);

    assertTrue(
        "Expected wait for quiescence to return immediately. Actual wait time was: "
            + TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS)
            + "ms",
        TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) <= 1);
  }
 public AuctionDataPersistedCache(String name, String root) {
   super(
       PersistedCacheType.ASYNCHRONIZED,
       name,
       TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES),
       TimeUnit.MILLISECONDS.convert(365, TimeUnit.DAYS),
       TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES),
       TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES));
   this.root = root;
 }
Exemple #5
0
 public void a(int i, bxa bxa1) {
   long l = b.getLong(c(i), 0L);
   long l1 = ((gwu) hlp.a(a, gwu)).a();
   if (l1 < TimeUnit.MILLISECONDS.convert(1L, TimeUnit.DAYS) + l) {
     a(i, 2591);
     a(i, bxa1.d);
   }
   if (l1 < l + TimeUnit.MILLISECONDS.convert(7L, TimeUnit.DAYS)) {
     a(i, 2595);
     a(i, bxa1.e);
   }
 }
Exemple #6
0
 public String printAvg(String unitName, double cnt) {
   endNs = System.nanoTime();
   long elapsedNs = endNs - startNs;
   long avgNs = _avg(elapsedNs, cnt);
   return String.format(
       "Completed %s %s in %s ms.  AvgPer: %s ms/%s \u00b5s/%s ns.",
       cnt,
       unitName,
       TimeUnit.MILLISECONDS.convert(elapsedNs, TimeUnit.NANOSECONDS),
       TimeUnit.MILLISECONDS.convert(avgNs, TimeUnit.NANOSECONDS),
       TimeUnit.MICROSECONDS.convert(avgNs, TimeUnit.NANOSECONDS),
       avgNs);
 }
Exemple #7
0
  @WdprMethodLog
  private static void loadCustomerDetails(Customer customer)
      throws ClassNotFoundException, IOException, SQLException, Exception {
    Connection conn = null;
    PreparedStatement statement = null;
    ResultSet rs = null;

    try {
      logging.debug(" Start loadCustomer");
      DBConnectionFactory dbFactory = DBConnectionFactory.getInstance();
      conn = dbFactory.getConnection();
      long queryStartTime = System.nanoTime();

      queryStartTime = System.nanoTime();
      String sql = buildInsertQuery(customer);
      statement = conn.prepareStatement(sql);
      statement = populateValues(customer, statement);
      rs = statement.executeQuery();
      long queryEndTime = System.nanoTime();
      logging.info(
          "Total_time_PS_loadCustomer : taken to execute loadCustomer query:="
              + TimeUnit.MILLISECONDS.convert(
                  (queryEndTime - queryStartTime), TimeUnit.NANOSECONDS));

      logging.debug(" End time of loadCustomer Query : ");
    } catch (Exception ex) {
      logging.error(ex.getLocalizedMessage());
      throw ex;

    } finally {
      if (rs != null) rs.close();
      if (statement != null) statement.close();
      if (conn != null) conn.close();
    }
  }
  @Test
  public void testPartitionedReferencePileThroughput() throws InterruptedException {
    int backlog = 64 * 1024;
    long start = System.nanoTime();

    PartitionedReferencePile<Slot> pile = new PartitionedReferencePile<Slot>(backlog, Slot::new);
    CountDownLatch latch = new CountDownLatch(threadCnt);
    for (int i = 0; i < threadCnt; i++) {
      int idx = i;
      pool.submit(
          () -> {
            for (int j = 0; j < backlog; j++) {
              Slot s = pile.get();
              s.var0 = idx;
              s.var1 = j;
            }

            for (Slot s : pile) {
              int slotIdx = s.var0;
            }
            latch.countDown();
          });
    }
    latch.await(5, TimeUnit.SECONDS);

    long end = System.nanoTime();
    double elapsed = TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS);
    System.out.println(
        String.format("throughput: %s ops/ms", (long) ((threadCnt * backlog) / elapsed)));
  }
  @Override
  public void yield(final long period, final TimeUnit timeUnit) {
    final long yieldMillis = TimeUnit.MILLISECONDS.convert(period, timeUnit);
    yieldExpiration.set(Math.max(yieldExpiration.get(), System.currentTimeMillis() + yieldMillis));

    processScheduler.yield(this);
  }
  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
    TimeUnit sessionUnit = TimeUnit.MILLISECONDS;
    long timeLeft = -1;
    long timeOutInMills =
        timeout < 0
            ? -1
            : TimeUnit.MILLISECONDS.convert(timeout, unit) + System.currentTimeMillis();

    if (getNumberofActiveJobs() == 0) {
      return true;
    }

    for (GearmanJobServerSession curSession : sessionsMap.values()) {
      if (!(curSession.isInitialized())) {
        continue;
      }
      // negative timeout means block till completion
      if (timeout >= 0) {
        timeLeft = timeOutInMills - System.currentTimeMillis();
        if (timeLeft <= 0) {
          LOG.warn("awaitTermination exceeded timeout.");
          break;
        }
      }
      try {
        curSession.waitForTasksToComplete(timeLeft, sessionUnit);
      } catch (TimeoutException te) {
        LOG.info("timed out waiting for all tasks to complete");
        break;
      }
    }
    return getNumberofActiveJobs() == 0;
  }
Exemple #11
0
  public Ec2Context(Ec2Credentials credentials) {
    this.credentials = credentials;
    Properties properties = new Properties();
    long scriptTimeout = TimeUnit.MILLISECONDS.convert(50, TimeUnit.MINUTES);
    properties.setProperty(TIMEOUT_SCRIPT_COMPLETE, scriptTimeout + "");
    properties.setProperty(TIMEOUT_PORT_OPEN, scriptTimeout + "");
    properties.setProperty(PROPERTY_CONNECTION_TIMEOUT, scriptTimeout + "");
    properties.setProperty(
        PROPERTY_EC2_AMI_QUERY, "owner-id=137112412989;state=available;image-type=machine");
    properties.setProperty(PROPERTY_EC2_CC_AMI_QUERY, "");
    properties.setProperty(
        Constants.PROPERTY_MAX_RETRIES, Settings.JCLOUDS_PROPERTY_MAX_RETRIES + "");
    properties.setProperty(
        Constants.PROPERTY_RETRY_DELAY_START, Settings.JCLOUDS_PROPERTY_RETRY_DELAY_START + "");

    Iterable<Module> modules =
        ImmutableSet.<Module>of(
            new SshjSshClientModule(),
            new SLF4JLoggingModule(),
            new EnterpriseConfigurationModule());

    ContextBuilder build =
        ContextBuilder.newBuilder("aws-ec2")
            .credentials(credentials.getAccessKey(), credentials.getSecretKey())
            .modules(modules)
            .overrides(properties);
    ComputeServiceContext context = build.buildView(ComputeServiceContext.class);
    this.computeService = (AWSEC2ComputeService) context.getComputeService();
    this.ec2api = computeService.getContext().unwrapApi(EC2Api.class);
    this.securityGroupApi = ec2api.getSecurityGroupApi().get();
    this.keypairApi = (AWSKeyPairApi) ec2api.getKeyPairApi().get();

    vmBatchSize = Settings.AWS_VM_BATCH_SIZE();
  }
 @Override
 public V get(long timeout, TimeUnit unit)
     throws InterruptedException, TimeoutException, ExecutionException {
   long tryLockStart = System.currentTimeMillis();
   if (!lock.tryLock(timeout, unit)) {
     throw new TimeoutException();
   }
   try {
     if (hasResult) {
       return getCachedResult();
     }
     long remainingDeadline =
         TimeUnit.MILLISECONDS.convert(timeout, unit)
             - (System.currentTimeMillis() - tryLockStart);
     try {
       K value;
       try {
         value = parent.get(remainingDeadline, TimeUnit.MILLISECONDS);
       } catch (ExecutionException ex) {
         return handleParentException(ex.getCause());
       }
       return wrapAndCache(value);
     } catch (InterruptedException ex) {
       throw ex;
     } catch (TimeoutException ex) {
       throw ex;
     } catch (Throwable ex) {
       throw setExceptionResult(convertException(ex));
     }
   } finally {
     lock.unlock();
   }
 }
 /**
  * The main method to check the mappabilities of the given read file names.
  *
  * @param btOutputFileName BowTie output file name
  * @param fileTileLength Tile length
  * @param outputFileName Output file name which the result will be saved into
  * @param readFileName Reads file name
  * @param chr1FileLines chromosome file name
  * @throws IOException
  */
 public void checkMappability(
     String btOutputFileName,
     int fileTileLength,
     String outputFileName,
     String readFileName,
     List<String> chr1FileLines)
     throws IOException {
   System.out.println("Creating [" + outputFileName + "]...");
   StopWatch stopWatch = new StopWatch();
   stopWatch.start();
   System.out.println("Reading [" + btOutputFileName + "]");
   List<String> btOutputFileLines = FileUtils.getInstance().readFile(btOutputFileName);
   System.out.println("Done reading [" + btOutputFileName + "]");
   System.out.println("Reading [" + readFileName + "]");
   List<String> readFileLines = FileUtils.getInstance().readFile(readFileName);
   System.out.println("Done reading [" + readFileName + "]");
   Map<String, Mappability> result =
       createMappability(btOutputFileLines, readFileLines, chr1FileLines);
   FileUtils.getInstance().writeFile(result, outputFileName, fileTileLength);
   stopWatch.stop();
   System.out.println(
       "["
           + outputFileName
           + "] is done in ["
           + TimeUnit.MILLISECONDS.convert(stopWatch.getNanoTime(), TimeUnit.NANOSECONDS)
           + "] MILLISECONDS");
 }
 @Override
 public List<MessageContext> readMessages(int itemsToPop, long timeout, TimeUnit units)
     throws MessageQueueException, BusyLockException, InterruptedException {
   long timeoutTime =
       (timeout == 0)
           ? 0
           : System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(timeout, units);
   // Loop while trying to get messages.
   // TODO: Make it possible to cancel this loop
   // TODO: Read full itemsToPop instead of just stopping when we get the first successful set
   List<MessageContext> messages = null;
   while (true) {
     MessageQueueShard partition = queue.shardReaderPolicy.nextShard();
     if (partition != null) {
       try {
         messages = readAndReturnShard(partition, itemsToPop);
         if (messages != null && !messages.isEmpty()) {
           return messages;
         }
       } finally {
         queue.shardReaderPolicy.releaseShard(partition, messages == null ? 0 : messages.size());
       }
     }
     if (timeoutTime != 0 && System.currentTimeMillis() > timeoutTime) {
       return Lists.newLinkedList();
     }
     Thread.sleep(queue.shardReaderPolicy.getPollInterval());
   }
 }
  @Override
  public void run() {
    if (!canExecute()) {
      LOGGER.warn("BotStarter.run() : Unable to acquire clustered lock, not running");
      return;
    }

    LOGGER.info("BotStarter.run() : Successfully acquired BotStarter lock");
    ExecutorService executorService = MMXExecutors.getOrCreate(THREAD_POOL_NAME, THREAD_POOL_SIZE);
    long startTime = System.nanoTime();
    AppDAO appDAO = new AppDAOImpl(getConnectionProvider());
    List<AppEntity> apps = appDAO.getAllApps();

    for (AppEntity app : apps) {
      String appName = app.getName().toLowerCase();
      if (isBotEnabled(appName)) {
        LOGGER.debug("Creating bot for app name:{} and id:{}", appName, app.getAppId());
        startApplicableBots(appName, app.getAppId(), executorService);
      } else {
        LOGGER.debug("Not creating bot for app name:{} and id:{}", appName, app.getId());
      }
    }

    long endTime = System.nanoTime();
    LOGGER.info(
        "Completed run execution in {} milliseconds",
        TimeUnit.MILLISECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS));
  }
 public void bubbleSortOptimized() {
   long start = System.nanoTime();
   long current;
   long diff = 0;
   int outer, inner;
   Link c = first;
   // count how many times
   for (outer = 0; outer < length2() - 2; outer++) { // forward
     // This next loop becomes shorter and shorter
     for (inner = 0; inner < (length1() - outer); inner++) // backward
     {
       if (c.getNext() != null && (int) c.getData() > (int) c.getNext().getData()) {
         int tmp = (int) c.getNext().getData();
         c.getNext().setData(c.getData());
         c.setData(tmp);
       }
       c = c.getNext();
     }
     c = first;
   }
   current = System.nanoTime();
   diff = (current - start);
   double seconds = TimeUnit.MILLISECONDS.convert(diff, TimeUnit.NANOSECONDS);
   System.out.println("Time Milliseconds: " + seconds + ", nanoseconds: " + diff);
 }
 /**
  * Method that schedule in the executor a periodic tasks. It calls the method of its parent class
  * using the super keyword and stores the period of the task.
  */
 @Override
 public ScheduledFuture<?> scheduleAtFixedRate(
     Runnable command, long initialDelay, long period, TimeUnit unit) {
   ScheduledFuture<?> task = super.scheduleAtFixedRate(command, initialDelay, period, unit);
   MyScheduledTask<?> myTask = (MyScheduledTask<?>) task;
   myTask.setPeriod(TimeUnit.MILLISECONDS.convert(period, unit));
   return task;
 }
 private void applyEndTime(CommandLine line) {
   if (line.hasOption(END_TIME)) {
     endTime = new Date(Long.parseLong(line.getOptionValue(END_TIME)));
   } else {
     endTime =
         new Date(System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(1L, TimeUnit.HOURS));
   }
 }
Exemple #19
0
 @Override
 public boolean setIfEmpty(T data, long time, TimeUnit units) {
   long end = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(time, units);
   while (!setIfEmpty(data)) {
     if (end < System.currentTimeMillis()) return false;
   }
   return true;
 }
 @Test
 public void testMillisToHMS() {
   long lHours = TimeUnit.HOURS.convert(12783000, TimeUnit.MILLISECONDS);
   TestCase.assertEquals(3, lHours);
   long lMinutes =
       TimeUnit.MINUTES.convert(
           12783000 - TimeUnit.MILLISECONDS.convert(lHours, TimeUnit.HOURS),
           TimeUnit.MILLISECONDS);
   TestCase.assertEquals(33, lMinutes);
   long lSeconds =
       TimeUnit.SECONDS.convert(
           12783000
               - (TimeUnit.MILLISECONDS.convert(lHours, TimeUnit.HOURS)
                   + TimeUnit.MILLISECONDS.convert(lMinutes, TimeUnit.MINUTES)),
           TimeUnit.MILLISECONDS);
   TestCase.assertEquals(3, lSeconds);
 }
 public InvocationCombiner(
     AccumulativeRunnable<PARAM_TYPE> pRunnable,
     long pDelayTime,
     TimeUnit pTimeUnit,
     ScheduledExecutorService pExecutor) {
   mRunnable =
       new ThrottleRunnable<PARAM_TYPE>(
           pRunnable, TimeUnit.MILLISECONDS.convert(pDelayTime, pTimeUnit), pExecutor);
 }
 /**
  * Returns the timeout value in milliseconds to use for the specifed API call.
  *
  * @param name the name of the API call (configuration key is "timeout." + name
  * @param defaultValue the default value to use if the name wasn't configured explicitely
  * @param timeUnit the TimeUnit of the default value
  * @return the timeout in milliseconds
  */
 public static long apiTimeout(final String name, Integer defaultValue, TimeUnit timeUnit) {
   try {
     final Long configuredMillis = timeoutValues.get(name);
     if (configuredMillis == Long.MIN_VALUE) {
       return defaultValue == null
           ? TimeUnit.MILLISECONDS.convert(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
           : TimeUnit.MILLISECONDS.convert(defaultValue, timeUnit);
     }
     return configuredMillis;
   } catch (ExecutionException ignored) {
     // we will never reach this
     LOG.error(
         "Unable to read timeout, this should never happen! Returning default timeout of "
             + DEFAULT_TIMEOUT
             + " seconds.");
     return DEFAULT_TIMEOUT;
   }
 }
 @Override
 public WebElementFacade withTimeoutOf(int timeout, TimeUnit unit) {
   return wrapWebElement(
       driver,
       getElement(),
       implicitTimeoutInMilliseconds,
       TimeUnit.MILLISECONDS.convert(timeout, unit),
       foundBy);
 }
  @Test
  public void testDays() {
    ClassWithDays ec = cof.build(ClassWithDays.class);

    Assert.assertEquals(5, ec.getValue().getPeriod());
    Assert.assertEquals(TimeUnit.DAYS, ec.getValue().getUnit());
    Assert.assertEquals(new TimeSpan(5, TimeUnit.DAYS), ec.getValue());
    Assert.assertEquals(TimeUnit.MILLISECONDS.convert(5, TimeUnit.DAYS), ec.getValue().getMillis());
  }
 /**
  * @return A 5-element array, containing the Unix time in milliseconds, time since {@link
  *     GaitAnalysis} instance is created in nanoseconds, and the 3 sensor values.
  */
 public String[] getStringArray() {
   String[] array = new String[4];
   array[0] =
       String.valueOf(TimeUnit.MILLISECONDS.convert(getTimeSinceStart(), TimeUnit.NANOSECONDS));
   array[1] = String.valueOf(x);
   array[2] = String.valueOf(y);
   array[3] = String.valueOf(z);
   return array;
 }
  @Override
  public AtmosphereResource suspend(long timeout, TimeUnit timeunit) {
    long timeoutms = -1;
    if (timeunit != null) {
      timeoutms = TimeUnit.MILLISECONDS.convert(timeout, timeunit);
    }

    return suspend(timeoutms);
  }
Exemple #27
0
 public void finish(String name, long threshHold, TimeUnit tu) {
   long dur = finish(name);
   if (logger.isDebugEnabled()) {
     long thresholdMillis = TimeUnit.MILLISECONDS.convert(threshHold, tu);
     if (dur > thresholdMillis) {
       throw new IllegalStateException(
           name + " took longer than " + threshHold + " " + tu.name().toLowerCase());
     }
   }
 }
  @Test
  public void testWaitForQuiescenceSuccessful() throws IOException, InterruptedException {
    mockServer
        .when(request().withMethod("GET").withPath("/quiescencesuccessful"), Times.exactly(1))
        .respond(response().withStatusCode(200).withDelay(new Delay(TimeUnit.SECONDS, 4)));

    final AtomicLong requestComplete = new AtomicLong();

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                try (CloseableHttpClient client =
                    NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
                  HttpResponse response =
                      client.execute(
                          new HttpGet(
                              "http://127.0.0.1:" + mockServerPort + "/quiescencesuccessful"));
                  EntityUtils.consumeQuietly(response.getEntity());

                  requestComplete.set(System.nanoTime());

                  assertEquals(
                      "Expected successful response from server",
                      200,
                      response.getStatusLine().getStatusCode());
                } catch (IOException e) {
                  fail("Error occurred while connecting to server");
                  log.error("Error occurred while connecting to server", e);
                }
              }
            })
        .start();

    // wait for the request to start before waiting for quiescence
    Thread.sleep(1000);

    boolean waitSuccessful = proxy.waitForQuiescence(2, 10, TimeUnit.SECONDS);

    long waitForQuiescenceFinished = System.nanoTime();

    assertTrue("Expected to successfully wait for quiescence", waitSuccessful);
    assertTrue(
        "Expected request to be complete after waiting for quiescence", requestComplete.get() > 0);

    // the total wait time after the request is complete should be approximately 2 seconds
    long wait =
        TimeUnit.MILLISECONDS.convert(
            waitForQuiescenceFinished - requestComplete.get(), TimeUnit.NANOSECONDS);

    assertTrue(
        "Expected time to wait for quiescence to be approximately 2s. Waited for: " + wait + "ms",
        wait < 3000);
  }
Exemple #29
0
  private void pushDataToChannel(
      Channel channel, String field, int numSamples, int samplePeriod, TimeUnit unit) {

    long periodMs = TimeUnit.MILLISECONDS.convert(samplePeriod, unit);

    for (int i = 0; i < numSamples; i++) {
      BasicDBObject sample = new BasicDBObject(Sample.TS_KEY, i * periodMs);
      sample.append(Sample.DATA_KEY, new BasicDBObject("v", i));
      channel.pushSample(sample, false, new BasicDBList());
    }
  }
  /**
   * Flush the buffer by looping until the {@link Buffer} is empty
   *
   * @param connection the {@link org.glassfish.grizzly.Connection}.
   * @param dstAddress the destination address.
   * @param message
   * @param currentResult the result of the write operation
   * @param timeout operation timeout value value
   * @param timeunit the timeout unit
   * @return The number of bytes written.
   * @throws java.io.IOException
   */
  protected long write0(
      final NIOConnection connection,
      final SocketAddress dstAddress,
      final WritableMessage message,
      final WriteResult<WritableMessage, SocketAddress> currentResult,
      final long timeout,
      final TimeUnit timeunit)
      throws IOException {

    final SelectableChannel channel = connection.getChannel();
    final long writeTimeout = TimeUnit.MILLISECONDS.convert(timeout, timeunit);

    SelectionKey key = null;
    Selector writeSelector = null;
    int attempts = 0;
    int bytesWritten = 0;

    try {
      synchronized (connection) {
        while (message.hasRemaining()) {
          long len = writeNow0(connection, dstAddress, message, currentResult);

          if (len > 0) {
            attempts = 0;
            bytesWritten += len;
          } else {
            attempts++;
            if (writeSelector == null) {
              writeSelector = transport.getTemporarySelectorIO().getSelectorPool().poll();

              if (writeSelector == null) {
                // Continue using the main one.
                continue;
              }
              key = channel.register(writeSelector, SelectionKey.OP_WRITE);
            } else {
              writeSelector.selectedKeys().clear();
            }

            if (writeSelector.select(writeTimeout) == 0) {
              if (attempts > 2) {
                throw new IOException("Client disconnected");
              }
            }
          }
        }
      }
    } finally {
      transport.getTemporarySelectorIO().recycleTemporaryArtifacts(writeSelector, key);
    }

    return bytesWritten;
  }