|
| 1 | +/* |
| 2 | + * Copyright 2000-2025 Vaadin Ltd. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 5 | + * use this file except in compliance with the License. You may obtain a copy of |
| 6 | + * 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, WITHOUT |
| 12 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | + * License for the specific language governing permissions and limitations under |
| 14 | + * the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.vaadin.base.devserver; |
| 18 | + |
| 19 | +import java.util.Objects; |
| 20 | +import java.util.concurrent.ThreadFactory; |
| 21 | +import java.util.concurrent.atomic.AtomicInteger; |
| 22 | + |
| 23 | +/** |
| 24 | + * A factory for creating daemon threads with custom naming conventions, used to |
| 25 | + * generate threads with a predefined naming pattern. |
| 26 | + * <p> |
| 27 | + * </p> |
| 28 | + * This class implements the {@link ThreadFactory} interface to provide a |
| 29 | + * mechanism for instantiating threads that are configured with specific |
| 30 | + * attributes such as name prefix, thread priority, and daemon status. |
| 31 | + */ |
| 32 | +public class NamedDaemonThreadFactory implements ThreadFactory { |
| 33 | + private final AtomicInteger threadNumber = new AtomicInteger(1); |
| 34 | + |
| 35 | + private final String namePrefix; |
| 36 | + |
| 37 | + /** |
| 38 | + * Constructs a new {@code NamedDaemonThreadFactory} with the specified name |
| 39 | + * prefix for the threads created by this factory. |
| 40 | + * |
<
9AF4
tr class="diff-line-row">
| 41 | + * @param namePrefix |
| 42 | + * the prefix to be used for naming threads created by this |
| 43 | + * factory, not {@literal null}. |
| 44 | + */ |
| 45 | + public NamedDaemonThreadFactory(String namePrefix) { |
| 46 | + this.namePrefix = Objects.requireNonNull(namePrefix, |
| 47 | + "namePrefix must not be null"); |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + public Thread newThread(Runnable runnable) { |
| 52 | + String threadName = namePrefix + "-" + threadNumber.getAndIncrement(); |
| 53 | + Thread thread = new Thread(runnable, threadName); |
| 54 | + thread.setDaemon(true); |
| 55 | + thread.setPriority(Thread.NORM_PRIORITY); |
| 56 | + return thread; |
| 57 | + } |
| 58 | +} |
0 commit comments