1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.apache.giraph.utils;
19
20 import java.util.ArrayList;
21 import java.util.List;
22
23 /**
24 * Makes a list of {@link ProgressCounter} accessible through
25 * a {@link ThreadLocal}.
26 */
27 public class ThreadLocalProgressCounter extends ThreadLocal<ProgressCounter> {
28 /**
29 * List of counters.
30 */
31 private final List<ProgressCounter> counters = new ArrayList<>();
32
33 /**
34 * Initializes a new counter, adds it to the list of counters
35 * and returns it.
36 * @return Progress counter.
37 */
38 @Override
39 protected ProgressCounter initialValue() {
40 ProgressCounter threadCounter = new ProgressCounter();
41 synchronized (counters) {
42 counters.add(threadCounter);
43 }
44 return threadCounter;
45 }
46
47 /**
48 * Sums the progress of all counters.
49 * @return Sum of all counters
50 */
51 public long getProgress() {
52 long progress = 0;
53 synchronized (counters) {
54 for (ProgressCounter entry : counters) {
55 progress += entry.getValue();
56 }
57 }
58 return progress;
59 }
60
61 /**
62 * Removes all counters.
63 */
64 public void reset() {
65 counters.clear();
66 }
67 }