/hazelcast/src/main/java/com/hazelcast/util/ThreadWatcher.java

https://bitbucket.org/gabral6_gmailcom/hazelcast · Java · 59 lines · 39 code · 5 blank · 15 comment · 7 complexity · 1a318699df4c5d1114d5d0a7962aad28 MD5 · raw file

  1. /*
  2. * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.hazelcast.util;
  17. public class ThreadWatcher {
  18. long start = 0;
  19. long totalWait = 0;
  20. long totalTime = 0;
  21. long waitCount = 0;
  22. long runCount = 0;
  23. public void addWait(long totalWaitNanos, long now) {
  24. if (start == 0) {
  25. start = now;
  26. } else {
  27. totalWait += totalWaitNanos;
  28. totalTime += (now - start);
  29. start = now;
  30. }
  31. waitCount++;
  32. }
  33. public long incrementRunCount() {
  34. long now = System.nanoTime();
  35. if (start == 0) {
  36. start = now;
  37. } else {
  38. totalTime += (now - start);
  39. start = now;
  40. }
  41. return runCount++;
  42. }
  43. public ThreadStats publish(boolean running) {
  44. long now = System.nanoTime();
  45. totalTime += (now - start);
  46. long totalRun = totalTime - totalWait;
  47. int utilizationPercentage = (totalTime <= 0 || runCount <= 1) ? 0 : (int) ((totalRun * 100L) / totalTime);
  48. ThreadStats threadStats = new ThreadStats(utilizationPercentage, runCount, waitCount, running);
  49. start = now;
  50. totalTime = 0;
  51. totalWait = 0;
  52. return threadStats;
  53. }
  54. }