001/*
002 * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.tribuo.common.nearest;
018
019import com.google.protobuf.Any;
020import com.google.protobuf.InvalidProtocolBufferException;
021import com.oracle.labs.mlrg.olcut.util.Pair;
022import com.oracle.labs.mlrg.olcut.util.StreamUtil;
023import org.tribuo.Example;
024import org.tribuo.Excuse;
025import org.tribuo.ImmutableFeatureMap;
026import org.tribuo.ImmutableOutputInfo;
027import org.tribuo.Model;
028import org.tribuo.Output;
029import org.tribuo.Prediction;
030import org.tribuo.common.nearest.KNNTrainer.Distance;
031import org.tribuo.common.nearest.protos.KNNModelProto;
032import org.tribuo.ensemble.EnsembleCombiner;
033import org.tribuo.impl.ModelDataCarrier;
034import org.tribuo.math.la.DenseVector;
035import org.tribuo.math.la.SGDVector;
036import org.tribuo.math.la.SparseVector;
037import org.tribuo.math.la.Tensor;
038import org.tribuo.math.neighbour.NeighboursQuery;
039import org.tribuo.math.neighbour.NeighboursQueryFactory;
040import org.tribuo.math.neighbour.bruteforce.NeighboursBruteForceFactory;
041import org.tribuo.math.protos.TensorProto;
042import org.tribuo.protos.ProtoUtil;
043import org.tribuo.protos.core.ModelProto;
044import org.tribuo.protos.core.OutputProto;
045import org.tribuo.provenance.ModelProvenance;
046
047import java.io.IOException;
048import java.security.AccessController;
049import java.security.PrivilegedAction;
050import java.util.ArrayList;
051import java.util.Collections;
052import java.util.List;
053import java.util.Map;
054import java.util.Objects;
055import java.util.Optional;
056import java.util.PriorityQueue;
057import java.util.concurrent.ExecutionException;
058import java.util.concurrent.ExecutorService;
059import java.util.concurrent.Executors;
060import java.util.concurrent.ForkJoinPool;
061import java.util.concurrent.ForkJoinWorkerThread;
062import java.util.concurrent.Future;
063import java.util.function.Function;
064import java.util.logging.Level;
065import java.util.logging.Logger;
066import java.util.stream.Collectors;
067import java.util.stream.Stream;
068
069/**
070 * A k-nearest neighbours model.
071 * <p>
072 * Note multi-threaded prediction uses a {@link ForkJoinPool} which requires that the Tribuo codebase
073 * is given the "modifyThread" and "modifyThreadGroup" privileges when running under a
074 * {@link java.lang.SecurityManager}.
075 */
076public class KNNModel<T extends Output<T>> extends Model<T> {
077
078    private static final Logger logger = Logger.getLogger(KNNModel.class.getName());
079
080    private static final long serialVersionUID = 1L;
081
082    /**
083     * Protobuf serialization version.
084     */
085    public static final int CURRENT_VERSION = 0;
086
087    // Thread factory for the FJP, to allow use with OpenSearch's SecureSM
088    private static final CustomForkJoinWorkerThreadFactory THREAD_FACTORY = new CustomForkJoinWorkerThreadFactory();
089
090    /**
091     * The parallel backend for batch predictions.
092     */
093    public enum Backend {
094        /**
095         * Uses the streams API for parallelism when scoring a batch of predictions.
096         */
097        STREAMS,
098        /**
099         * Uses a thread pool at the outer level (i.e., one thread per prediction).
100         */
101        THREADPOOL,
102        /**
103         * Uses a thread pool at the inner level (i.e., the whole thread pool works on each prediction).
104         */
105        INNERTHREADPOOL
106    }
107
108    private final Pair<SGDVector,T>[] vectors;
109
110    private final int k;
111    @Deprecated
112    private Distance distance;
113
114    // This is not final to support deserialization of older models. It will be final in a future version which doesn't
115    // maintain serialization compatibility with 4.X.
116    private org.tribuo.math.distance.Distance dist;
117
118    private final int numThreads;
119
120    private final Backend parallelBackend;
121
122    private final EnsembleCombiner<T> combiner;
123
124    // This is not final to support deserialization of older models. It will be final in a future version which doesn't
125    // maintain serialization compatibility with 4.X.
126    private NeighboursQueryFactory neighboursQueryFactory;
127
128    private transient NeighboursQuery neighboursQuery;
129
130    KNNModel(String name, ModelProvenance provenance, ImmutableFeatureMap featureIDMap, ImmutableOutputInfo<T> outputIDInfo,
131             boolean generatesProbabilities, int k, org.tribuo.math.distance.Distance dist, int numThreads, EnsembleCombiner<T> combiner,
132             Pair<SGDVector,T>[] vectors, Backend backend, NeighboursQueryFactory neighboursQueryFactory) {
133        super(name,provenance,featureIDMap,outputIDInfo,generatesProbabilities);
134        this.k = k;
135        this.dist = dist;
136        this.numThreads = numThreads;
137        this.combiner = combiner;
138        this.parallelBackend = backend;
139        this.vectors = vectors;
140        this.neighboursQueryFactory = neighboursQueryFactory;
141        this.neighboursQuery = neighboursQueryFactory.createNeighboursQuery(getSGDVectorArr());
142    }
143
144    /**
145     * Deserialization factory.
146     * @param version The serialized object version.
147     * @param className The class name.
148     * @param message The serialized data.
149     * @throws InvalidProtocolBufferException If the protobuf could not be parsed from the {@code message}.
150     * @return The deserialized object.
151     */
152    @SuppressWarnings({"unchecked","rawtypes"}) // Guarded by getClass checks to ensure all outputs are the same type.
153    public static KNNModel<?> deserializeFromProto(int version, String className, Any message) throws InvalidProtocolBufferException {
154        if (version < 0 || version > CURRENT_VERSION) {
155            throw new IllegalArgumentException("Unknown version " + version + ", this class supports at most version " + CURRENT_VERSION);
156        }
157        KNNModelProto proto = message.unpack(KNNModelProto.class);
158
159        ModelDataCarrier<?> carrier = ModelDataCarrier.deserialize(proto.getMetadata());
160        ImmutableFeatureMap featureDomain = carrier.featureDomain();
161        ImmutableOutputInfo<?> outputDomain = carrier.outputDomain();
162        Class<?> outputClass = outputDomain.getOutput(0).getClass();
163        EnsembleCombiner<?> combiner = EnsembleCombiner.deserialize(proto.getCombiner());
164        if (!outputClass.equals(combiner.getTypeWitness())) {
165            throw new IllegalStateException("Invalid protobuf, combiner and output domain have a type mismatch, expected " + outputClass + " found " + combiner.getTypeWitness());
166        }
167
168        int k = proto.getK();
169        if (k < 1) {
170            throw new IllegalStateException("Invalid protobuf, k must be positive, found " + k);
171        }
172        int numThreads = proto.getNumThreads();
173        if (numThreads < 0) {
174            throw new IllegalStateException("Invalid protobuf, numThreads must be positive, found " + numThreads);
175        }
176
177        if (proto.getVectorsCount() == 0) {
178            throw new IllegalStateException("Invalid protobuf, no vectors were found");
179        }
180        if (proto.getVectorsCount() != proto.getOutputsCount()) {
181            throw new IllegalStateException("Invalid protobuf, different numbers of outputs and vectors were found, " + proto.getVectorsCount() + " vectors, " + proto.getOutputsCount() + " outputs");
182        }
183        Pair<SGDVector, ?>[] pairs = new Pair[proto.getVectorsCount()];
184        List<TensorProto> vectorProtos = proto.getVectorsList();
185        List<OutputProto> outputProtos = proto.getOutputsList();
186        for (int i = 0; i < pairs.length; i++) {
187            Tensor vectorTensor = Tensor.deserialize(vectorProtos.get(i));
188            Output output = Output.deserialize(outputProtos.get(i));
189            if (vectorTensor instanceof SGDVector) {
190                SGDVector vector = (SGDVector) vectorTensor;
191                if (vector.size() != featureDomain.size()) {
192                    throw new IllegalStateException("Invalid protobuf, vector did not contain all the features, found " + vector.size() + " expected " + featureDomain.size());
193                }
194                if (output.getClass().equals(outputClass)) {
195                    pairs[i] = new Pair<>(vector,output);
196                } else {
197                    throw new IllegalStateException("Invalid protobuf, output type did not match, found " + output.getClass() + " expected " + outputClass);
198                }
199            } else {
200                throw new IllegalStateException("Invalid protobuf, expected centroid to be a vector, found " + vectorTensor.getClass());
201            }
202        }
203
204        org.tribuo.math.distance.Distance dist = ProtoUtil.deserialize(proto.getDistance());
205        Backend backend = Backend.valueOf(proto.getParallelBackend());
206        NeighboursQueryFactory queryFactory = NeighboursQueryFactory.deserialize(proto.getNeighboursQueryFactory());
207
208        return new KNNModel(carrier.name(), carrier.provenance(), featureDomain, outputDomain,
209            carrier.generatesProbabilities(), k, dist, numThreads, combiner, pairs, backend, queryFactory);
210    }
211
212    @Override
213    public Prediction<T> predict(Example<T> example) {
214        SGDVector input;
215        if (example.size() == featureIDMap.size()) {
216            input = DenseVector.createDenseVector(example, featureIDMap, false);
217        } else {
218            input = SparseVector.createSparseVector(example, featureIDMap, false);
219        }
220
221        if (input.numActiveElements() == 0) {
222            throw new IllegalArgumentException("No features found in Example " + example);
223        }
224
225        Function<Pair<SGDVector,T>, OutputDoublePair<T>> distanceFunc =
226            (a) -> new OutputDoublePair<>(a.getB(), dist.computeDistance(a.getA(), input));
227
228        List<Prediction<T>> predictions;
229        Stream<Pair<SGDVector,T>> stream = Stream.of(vectors);
230        if (numThreads > 1) {
231            ForkJoinPool fjp = System.getSecurityManager() == null ? new ForkJoinPool(numThreads) : new ForkJoinPool(numThreads, THREAD_FACTORY, null, false);
232            try {
233                predictions = fjp.submit(()->StreamUtil.boundParallelism(stream.parallel()).map(distanceFunc).sorted().limit(k).map((a) -> new Prediction<>(a.output, input.numActiveElements(), example)).collect(Collectors.toList())).get();
234            } catch (InterruptedException | ExecutionException e) {
235                logger.log(Level.SEVERE,"Exception when predicting in KNNModel",e);
236                throw new IllegalStateException("Failed to process example in parallel",e);
237            }
238        } else {
239            predictions = stream.map(distanceFunc).sorted().limit(k).map((a) -> new Prediction<>(a.output, input.numActiveElements(), example)).collect(Collectors.toList());
240        }
241
242        return combiner.combine(outputIDInfo,predictions);
243    }
244
245    /**
246     * Uses the model to predict the output for multiple examples.
247     * @param examples the examples to predict.
248     * @return the results of the prediction, in the same order as the
249     * examples.
250     */
251    @Override
252    protected List<Prediction<T>> innerPredict(Iterable<Example<T>> examples) {
253        if (numThreads > 1) {
254            return innerPredictMultithreaded(examples);
255        } else {
256            List<Prediction<T>> predictions = new ArrayList<>();
257            List<Prediction<T>> innerPredictions = new ArrayList<>();
258
259            for (Example<T> example : examples) {
260                innerPredictions.clear();
261                SGDVector input;
262                if (example.size() == featureIDMap.size()) {
263                    input = DenseVector.createDenseVector(example, featureIDMap, false);
264                } else {
265                    input = SparseVector.createSparseVector(example, featureIDMap, false);
266                }
267
268                List<Pair<Integer, Double>> indexDistancePairList = neighboursQuery.query(input, k);
269
270                for (Pair<Integer, Double> simplePair : indexDistancePairList) {
271                    Pair<SGDVector,T> pair = vectors[simplePair.getA()];
272                    innerPredictions.add(new Prediction<>(pair.getB(), input.numActiveElements(), example));
273                }
274
275                predictions.add(combiner.combine(outputIDInfo, innerPredictions));
276            }
277            return predictions;
278        }
279    }
280
281    /**
282     * Switches between the different multithreaded backends.
283     * @param examples The examples to predict.
284     * @return The predictions.
285     */
286    private List<Prediction<T>> innerPredictMultithreaded(Iterable<Example<T>> examples) {
287        switch (parallelBackend) {
288            case STREAMS:
289                logger.log(Level.FINE, "Parallel backend - streams");
290                return innerPredictStreams(examples);
291            case THREADPOOL:
292                logger.log(Level.FINE, "Parallel backend - threadpool");
293                return innerPredictThreadPool(examples);
294            case INNERTHREADPOOL:
295                logger.log(Level.FINE, "Parallel backend - within example threadpool");
296                return innerPredictWithinExampleThreadPool(examples);
297            default:
298                throw new IllegalArgumentException("Unknown backend " + parallelBackend);
299        }
300    }
301
302    /**
303     * Predicts using a FJP and the Streams API.
304     * @param examples The examples to predict.
305     * @return The predictions.
306     */
307    private List<Prediction<T>> innerPredictStreams(Iterable<Example<T>> examples) {
308        List<Prediction<T>> predictions = new ArrayList<>();
309        List<Prediction<T>> innerPredictions = null;
310        ForkJoinPool fjp = System.getSecurityManager() == null ? new ForkJoinPool(numThreads) : new ForkJoinPool(numThreads, THREAD_FACTORY, null, false);
311        for (Example<T> example : examples) {
312            SGDVector input;
313            if (example.size() == featureIDMap.size()) {
314                input = DenseVector.createDenseVector(example, featureIDMap, false);
315            } else {
316                input = SparseVector.createSparseVector(example, featureIDMap, false);
317            }
318
319            Function<Pair<SGDVector, T>, OutputDoublePair<T>> distanceFunc =
320                (a) -> new OutputDoublePair<>(a.getB(), dist.computeDistance(a.getA(), input));
321
322            Stream<Pair<SGDVector, T>> stream = Stream.of(vectors);
323            try {
324                innerPredictions = fjp.submit(() -> StreamUtil.boundParallelism(stream.parallel()).map(distanceFunc).sorted().limit(k).map((a) -> new Prediction<>(a.output, input.numActiveElements(), example)).collect(Collectors.toList())).get();
325            } catch (InterruptedException | ExecutionException e) {
326                logger.log(Level.SEVERE, "Exception when predicting in KNNModel", e);
327            }
328
329            predictions.add(combiner.combine(outputIDInfo, innerPredictions));
330        }
331
332        return predictions;
333    }
334
335    /**
336     * Uses a thread pool, one thread per prediction.
337     * @param examples The examples to predict.
338     * @return The predictions.
339     */
340    private List<Prediction<T>> innerPredictThreadPool(Iterable<Example<T>> examples) {
341        List<Prediction<T>> predictions = new ArrayList<>();
342
343        ExecutorService pool = Executors.newFixedThreadPool(numThreads);
344
345        List<Future<Prediction<T>>> futures = new ArrayList<>();
346
347        for (Example<T> example : examples) {
348            futures.add(pool.submit(() -> innerPredictOne(neighboursQuery,vectors,combiner,featureIDMap,outputIDInfo,k,example)));
349        }
350
351        try {
352            for (Future<Prediction<T>> f : futures) {
353                predictions.add(f.get());
354            }
355        } catch (InterruptedException | ExecutionException e) {
356            throw new IllegalStateException("Thread pool went bang",e);
357        }
358
359        pool.shutdown();
360
361        return predictions;
362    }
363
364    /**
365     * Uses a thread pool where the pool collaborates on each example (best for large training dataset sizes).
366     * @param examples The examples to predict.
367     * @return The predictions.
368     */
369    private List<Prediction<T>> innerPredictWithinExampleThreadPool(Iterable<Example<T>> examples) {
370
371        List<Prediction<T>> predictions = new ArrayList<>();
372
373        ExecutorService pool = Executors.newFixedThreadPool(numThreads);
374
375        ThreadLocal<PriorityQueue<OutputDoublePair<T>>> queuePool = ThreadLocal.withInitial(() -> new PriorityQueue<>(k, (a,b) -> Double.compare(b.value, a.value)));
376
377        for (Example<T> example : examples) {
378            predictions.add(innerPredictThreadPool(pool,queuePool,dist,example));
379        }
380
381        pool.shutdown();
382
383        return predictions;
384    }
385
386    private Prediction<T> innerPredictThreadPool(ExecutorService pool,
387                                                 ThreadLocal<PriorityQueue<OutputDoublePair<T>>> queuePool,
388                                                 org.tribuo.math.distance.Distance dist,
389                                                 Example<T> example) {
390        SparseVector vector = SparseVector.createSparseVector(example, featureIDMap, false);
391        List<Future<List<OutputDoublePair<T>>>> futures = new ArrayList<>();
392
393        for (int i = 0; i < numThreads; i++) {
394            int start = i * (vectors.length / numThreads);
395            int end = (i + 1) * (vectors.length / numThreads);
396            futures.add(pool.submit(() -> innerPredictChunk(queuePool,vectors,start,end,dist,k,vector)));
397        }
398
399        PriorityQueue<OutputDoublePair<T>> queue = new PriorityQueue<>(k, (a,b) -> Double.compare(b.value, a.value));
400        try {
401            for (Future<List<OutputDoublePair<T>>> f : futures) {
402                List<OutputDoublePair<T>> chunkOutputs = f.get();
403                for (OutputDoublePair<T> curOutputPair : chunkOutputs) {
404                    if (queue.size() < k) {
405                        queue.offer(curOutputPair);
406                    } else if (Double.compare(curOutputPair.value, queue.peek().value) < 0) {
407                        queue.poll();
408                        queue.offer(curOutputPair);
409                    }
410                }
411            }
412        } catch (InterruptedException | ExecutionException e) {
413            throw new IllegalStateException("Thread pool went bang",e);
414        }
415
416        List<Prediction<T>> predictions = new ArrayList<>();
417
418        for (OutputDoublePair<T> pair : queue) {
419            predictions.add(new Prediction<>(pair.output,vector.numActiveElements(),example));
420        }
421
422        return combiner.combine(outputIDInfo,predictions);
423    }
424
425    private static <T extends Output<T>> List<OutputDoublePair<T>> innerPredictChunk(ThreadLocal<PriorityQueue<OutputDoublePair<T>>> queuePool,
426                                                                            Pair<SGDVector,T>[] vectors,
427                                                                            int start,
428                                                                            int end,
429                                                                            org.tribuo.math.distance.Distance dist,
430                                                                            int k,
431                                                                            SGDVector input) {
432        PriorityQueue<OutputDoublePair<T>> queue = queuePool.get();
433        queue.clear();
434
435        end = Math.min(end, vectors.length);
436
437        for (int i = start; i < end; i++) {
438            double curDistance = dist.computeDistance(vectors[i].getA(), input);
439
440            if (queue.size() < k) {
441                OutputDoublePair<T> newPair = new OutputDoublePair<>(vectors[i].getB(),curDistance);
442                queue.offer(newPair);
443            } else if (Double.compare(curDistance, queue.peek().value) < 0) {
444                OutputDoublePair<T> pair = queue.poll();
445                pair.output = vectors[i].getB();
446                pair.value = curDistance;
447                queue.offer(pair);
448            }
449        }
450
451        return new ArrayList<>(queue);
452    }
453
454    private static <T extends Output<T>> Prediction<T> innerPredictOne(NeighboursQuery nq,
455                                                                    Pair<SGDVector,T>[] vectors,
456                                                                    EnsembleCombiner<T> combiner,
457                                                                    ImmutableFeatureMap featureIDMap,
458                                                                    ImmutableOutputInfo<T> outputIDInfo,
459                                                                    int k,
460                                                                    Example<T> example) {
461        SGDVector vector;
462        if (example.size() == featureIDMap.size()) {
463            vector = DenseVector.createDenseVector(example, featureIDMap, false);
464        } else {
465            vector = SparseVector.createSparseVector(example, featureIDMap, false);
466        }
467
468        List<Pair<Integer, Double>> indexDistancePairList = nq.query(vector, k);
469
470        List<Prediction<T>> localPredictions = new ArrayList<>();
471
472        for (Pair<Integer, Double> simplePair : indexDistancePairList) {
473            Pair<SGDVector,T> pair = vectors[simplePair.getA()];
474            localPredictions.add(new Prediction<>(pair.getB(), vector.numActiveElements(), example));
475        }
476
477        return combiner.combine(outputIDInfo,localPredictions);
478    }
479
480    @Override
481    public Map<String, List<Pair<String, Double>>> getTopFeatures(int n) {
482        return Collections.emptyMap();
483    }
484
485    @Override
486    public Optional<Excuse<T>> getExcuse(Example<T> example) {
487        return Optional.empty();
488    }
489
490    @Override
491    public ModelProto serialize() {
492        ModelDataCarrier<T> carrier = createDataCarrier();
493
494        KNNModelProto.Builder modelBuilder = KNNModelProto.newBuilder();
495        modelBuilder.setMetadata(carrier.serialize());
496        for (Pair<SGDVector,T> e : vectors) {
497            modelBuilder.addVectors(e.getA().serialize());
498            modelBuilder.addOutputs(e.getB().serialize());
499        }
500        modelBuilder.setK(k);
501        modelBuilder.setDistance(dist.serialize());
502        modelBuilder.setNumThreads(numThreads);
503        modelBuilder.setParallelBackend(parallelBackend.name());
504        modelBuilder.setCombiner(combiner.serialize());
505        modelBuilder.setNeighboursQueryFactory(neighboursQueryFactory.serialize());
506
507        ModelProto.Builder builder = ModelProto.newBuilder();
508        builder.setSerializedData(Any.pack(modelBuilder.build()));
509        builder.setClassName(KNNModel.class.getName());
510        builder.setVersion(CURRENT_VERSION);
511
512        return builder.build();
513    }
514
515    @SuppressWarnings("unchecked") // Generic array creation.
516    @Override
517    protected KNNModel<T> copy(String newName, ModelProvenance newProvenance) {
518        Pair<SGDVector,T>[] vectorCopy = new Pair[vectors.length];
519        for (int i = 0; i < vectors.length; i++) {
520            vectorCopy[i] = new Pair<>(vectors[i].getA().copy(),vectors[i].getB().copy());
521        }
522        return new KNNModel<>(newName,newProvenance,featureIDMap,outputIDInfo,generatesProbabilities,k,dist,
523            numThreads,combiner,vectorCopy,parallelBackend,neighboursQueryFactory);
524    }
525
526    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
527        in.defaultReadObject();
528        if (dist == null) {
529            dist = distance.getDistanceType().getDistance();
530        }
531        if (neighboursQueryFactory == null) {
532            neighboursQueryFactory = new NeighboursBruteForceFactory(dist, numThreads);
533        }
534        neighboursQuery = neighboursQueryFactory.createNeighboursQuery(getSGDVectorArr());
535    }
536
537    private SGDVector[] getSGDVectorArr() {
538        SGDVector[] sgdVectors = new SGDVector[vectors.length];
539        int n = 0;
540        for (Pair<SGDVector,T> vector : vectors) {
541            sgdVectors[n] = vector.getA();
542            n++;
543        }
544        return sgdVectors;
545    }
546
547    /**
548     * It's a specialised non-final pair used for buffering and to reduce object creation.
549     * @param <T> The output type.
550     */
551    private static final class OutputDoublePair<T extends Output<T>> implements Comparable<OutputDoublePair<T>> {
552        T output;
553        double value;
554
555        public OutputDoublePair(T output, double value) {
556            this.output = output;
557            this.value = value;
558        }
559
560        @Override
561        public boolean equals(Object o) {
562            if (this == o) return true;
563            if (o == null || getClass() != o.getClass()) return false;
564            OutputDoublePair<?> that = (OutputDoublePair<?>) o;
565            return Double.compare(that.value, value) == 0 &&
566                    output.equals(that.output);
567        }
568
569        @Override
570        public int hashCode() {
571            return Objects.hash(output, value);
572        }
573
574        @Override
575        public int compareTo(OutputDoublePair<T> o) {
576            return Double.compare(value, o.value);
577        }
578    }
579
580    /**
581     * Used to allow FJPs to work with OpenSearch's SecureSM.
582     */
583    private static final class CustomForkJoinWorkerThreadFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory {
584        public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
585            return AccessController.doPrivileged((PrivilegedAction<ForkJoinWorkerThread>) () -> new ForkJoinWorkerThread(pool) {});
586        }
587    }
588}