|
| 1 | +/* |
| 2 | + * Copyright 2015 MongoDB, Inc. |
| 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 | + */ |
| 17 | + |
| 18 | +package com.mongodb.internal.thread; |
| 19 | + |
| 20 | +import java.util.concurrent.ThreadFactory; |
| 21 | +import java.util.concurrent.atomic.AtomicInteger; |
| 22 | + |
| 23 | +/** |
| 24 | + * Custom thread factory for scheduled executor service that creates daemon threads. Otherwise, |
| 25 | + * applications that neglect to close the client will not exit. |
| 26 | + * |
| 27 | + * <p>This class should not be considered a part of the public API.</p> |
| 28 | + */ |
| 29 | +public class DaemonThreadFactory implements ThreadFactory { |
| 30 | + private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); |
| 31 | + private final AtomicInteger threadNumber = new AtomicInteger(1); |
| 32 | + private final String namePrefix; |
| 33 | + |
| 34 | + public DaemonThreadFactory() { |
| 35 | + this("pool"); |
| 36 | + } |
| 37 | + |
| 38 | + public DaemonThreadFactory(final String prefix) { |
| 39 | + namePrefix = prefix + "-" + POOL_NUMBER.getAndIncrement() + "-thread-"; |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public Thread newThread(final Runnable runnable) { |
| 44 | + Thread t = new Thread(runnable, namePrefix + threadNumber.getAndIncrement()); |
| 45 | + t.setDaemon(true); |
| 46 | + return t; |
| 47 | + } |
| 48 | +} |
0 commit comments