aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/dev/morling/onebrc/CalculateAverage_felix19350.java
blob: 8c047b72aea3f65af3eb47bbb1987dfbebb310fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
 *  Copyright 2023 The original authors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package dev.morling.onebrc;

import java.io.IOException;
import java.lang.foreign.Arena;
import java.lang.foreign.ValueLayout;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CalculateAverage_felix19350 {
    private static final String FILE = "./measurements.txt";
    private static final int NEW_LINE_SEEK_BUFFER_LEN = 128;

    private static final int EXPECTED_MAX_NUM_CITIES = 15_000; // 10K cities + a buffer no to trigger the load factor

    private static class CityRef {

        final int length;
        final int fingerprint;
        final byte[] stringBytes;

        public CityRef(ByteBuffer byteBuffer, int startIdx, int length, int fingerprint) {
            this.length = length;
            this.stringBytes = new byte[length];
            byteBuffer.get(startIdx, this.stringBytes, 0, this.stringBytes.length);
            this.fingerprint = fingerprint;
        }

        public String cityName() {
            return new String(stringBytes, StandardCharsets.UTF_8);
        }

        @Override
        public int hashCode() {
            return fingerprint;
        }

        @Override
        public boolean equals(Object other) {
            if (other instanceof CityRef otherRef) {
                if (fingerprint != otherRef.fingerprint) {
                    return false;
                }

                if (this.length != otherRef.length) {
                    return false;
                }

                for (var i = 0; i < this.length; i++) {
                    if (this.stringBytes[i] != otherRef.stringBytes[i]) {
                        return false;
                    }
                }
                return true;
            }
            else {
                return false;
            }
        }

    }

    private static class ResultRow {

        private int min;
        private int max;
        private int sum;
        private int count;

        public ResultRow(int initialValue) {
            this.min = initialValue;
            this.max = initialValue;
            this.sum = initialValue;
            this.count = 1;
        }

        public void mergeValue(int value) {
            this.min = Math.min(this.min, value);
            this.max = Math.max(this.max, value);
            this.sum += value;
            this.count += 1;
        }

        public String toString() {
            return round(min / 10.0) + "/" + round(sum / 10.0 / count) + "/" + round(max / 10.0);
        }

        private double round(double value) {
            return Math.round(value * 10.0) / 10.0;
        }

        public void mergeResult(ResultRow value) {
            min = Math.min(min, value.min);
            max = Math.max(max, value.max);
            sum += value.sum;
            count += value.count;
        }
    }

  private record AverageAggregatorTask(ByteBuffer byteBuffer) {
    private static final int HASH_FACTOR = 31; // Mersenne prime


    public static Stream<AverageAggregatorTask> createStreamOf(List<ByteBuffer> byteBuffers) {
      return byteBuffers.stream().map(AverageAggregatorTask::new);
    }

    public Map<CityRef, ResultRow> processChunk() {
      final var measurements = new HashMap<CityRef, ResultRow>(EXPECTED_MAX_NUM_CITIES);
      var lineStart = 0;
      // process line by line playing with the fact that a line is no longer than 106 bytes
      // 100 bytes for city name + 1 byte for separator + 1 bytes for negative sign + 4 bytes for number
      while (lineStart < byteBuffer.limit()) {
        lineStart = this.processLine(measurements, byteBuffer, lineStart);
      }
      return measurements;
    }

    private int processLine(Map<CityRef, ResultRow> measurements, ByteBuffer byteBuffer, int start) {
      var fingerPrint = 0;
      var separatorIdx = -1;
      var sign = 1;
      var value = 0;
      var lineEnd = -1;
      // Lines are processed in two stages:
      // 1 - prior do the city name separator
      // 2 - after the separator
      // this ensures less if clauses

      // stage 1 loop
      {
        for (int i = 0; i < NEW_LINE_SEEK_BUFFER_LEN; i++) {
          final var currentByte = byteBuffer.get(start + i);
          if (currentByte == ';') {
            separatorIdx = i;
            break;
          } else {
            fingerPrint = HASH_FACTOR * fingerPrint + currentByte;
          }
        }
      }

      // stage 2 loop:
      {
        for (int i = separatorIdx + 1; i < NEW_LINE_SEEK_BUFFER_LEN; i++) {
          final var currentByte = byteBuffer.get(start + i);
          switch (currentByte) {
            case '-':
              sign = -1;
              break;
            case '.':
              break;
            case '\n':
              lineEnd = start + i + 1;
              break;
            default:
              // only digits are expected here
              value = value * 10 + (currentByte - '0');
          }

          if (lineEnd != -1) {
            break;
          }
        }
      }

      assert (separatorIdx > 0);
      final var cityRef = new CityRef(byteBuffer, start, separatorIdx,fingerPrint);
      value = sign * value;

      final var existingMeasurement = measurements.get(cityRef);
      if (existingMeasurement == null) {
        measurements.put(cityRef, new ResultRow(value));
      } else {
        existingMeasurement.mergeValue(value);
      }

      return lineEnd; //to account for the line end
    }
  }

    public static void main(String[] args) throws IOException {
        // memory map the files and divide by number of cores
        final var numProcessors = Runtime.getRuntime().availableProcessors();
        final var byteBuffers = calculateMemorySegments(numProcessors);
        final var tasks = AverageAggregatorTask.createStreamOf(byteBuffers);
        assert (byteBuffers.size() <= numProcessors);
        assert (!byteBuffers.isEmpty());

        try (var pool = Executors.newFixedThreadPool(numProcessors)) {
            final Map<CityRef, ResultRow> aggregatedCities = tasks
                    .parallel()
                    .map(task -> CompletableFuture.supplyAsync(task::processChunk, pool))
                    .map(CompletableFuture::join)
                    .reduce(new HashMap<>(EXPECTED_MAX_NUM_CITIES), (currentMap, accumulator) -> {
                        currentMap.forEach((key, value) -> {
                            final var prev = accumulator.get(key);
                            if (prev == null) {
                                accumulator.put(key, value);
                            }
                            else {
                                prev.mergeResult(value);
                            }
                        });
                        return accumulator;
                    });

            var results = new HashMap<String, ResultRow>(EXPECTED_MAX_NUM_CITIES);
            aggregatedCities.forEach((key, value) -> results.put(key.cityName(), value));

            System.out.print("{");
            String output = results.keySet()
                    .stream()
                    .sorted()
                    .map(key -> key + "=" + results.get(key).toString())
                    .collect(Collectors.joining(", "));
            System.out.print(output);
            System.out.println("}");
        }
    }

    private static List<ByteBuffer> calculateMemorySegments(int numChunks) throws IOException {
        try (FileChannel fc = FileChannel.open(Paths.get(FILE))) {
            var memMappedFile = fc.map(FileChannel.MapMode.READ_ONLY, 0L, fc.size(), Arena.ofAuto());
            var result = new ArrayList<ByteBuffer>(numChunks);

            var fileSize = fc.size();
            var chunkSize = fileSize / numChunks; // TODO: if chunksize > MAX INT we will need to adjust
            var previousChunkEnd = 0L;

            for (int i = 0; i < numChunks; i++) {
                if (previousChunkEnd >= fileSize) {
                    // There is a scenario for very small files where the number of chunks may be greater than
                    // the number of lines.
                    break;
                }
                var chunk = new long[]{ previousChunkEnd, 0 };
                if (i == (numChunks - 1)) {
                    // ensure the last chunk covers the full file
                    chunk[1] = fileSize;
                }
                else {
                    // all other chunks are end at a new line (\n)
                    var theoreticalEnd = Math.min(previousChunkEnd + chunkSize, fileSize);
                    var newLineOffset = 0;
                    for (int j = 0; j < NEW_LINE_SEEK_BUFFER_LEN; j++) {
                        var candidateOffset = theoreticalEnd + j;
                        if (candidateOffset >= fileSize) {
                            break;
                        }
                        byte b = memMappedFile.get(ValueLayout.OfByte.JAVA_BYTE, candidateOffset);
                        newLineOffset += 1;
                        if ((char) b == '\n') {
                            break;
                        }
                    }
                    chunk[1] = Math.min(fileSize, theoreticalEnd + newLineOffset);
                    previousChunkEnd = chunk[1];
                }

                assert (chunk[1] > chunk[0]);
                assert (chunk[1] <= fileSize);

                result.add(memMappedFile.asSlice(chunk[0], (chunk[1] - chunk[0])).asByteBuffer());
            }
            return result;
        }
    }
}