View Javadoc
1   package fr.ifremer.quadrige3.synchro.server.technical;
2   
3   /*-
4    * #%L
5    * Quadrige3 Core :: Quadrige3 Synchro server
6    * $Id:$
7    * $HeadURL:$
8    * %%
9    * Copyright (C) 2017 Ifremer
10   * %%
11   * This program is free software: you can redistribute it and/or modify
12   * it under the terms of the GNU Affero General Public License as published by
13   * the Free Software Foundation, either version 3 of the License, or
14   * (at your option) any later version.
15   * 
16   * This program is distributed in the hope that it will be useful,
17   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   * GNU General Public License for more details.
20   * 
21   * You should have received a copy of the GNU Affero General Public License
22   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23   * #L%
24   */
25  
26  
27  import com.google.common.collect.Lists;
28  import fr.ifremer.quadrige3.core.dao.technical.Assert;
29  
30  import java.util.List;
31  
32  /**
33   * Utility class on Thread
34   * @author Benoit Lavenier <benoit.lavenier@e-is.pro>
35   * @since 1.0
36   */
37  public class ThreadUtils {
38  
39      protected ThreadUtils() {
40          // helper class
41      }
42      
43      public static Thread getThreadById(long id) {
44          for (Thread t: Thread.getAllStackTraces().keySet()) {
45              if (t.getId() == id) {
46                  return t;
47              }
48          }
49          
50          return null;
51      }
52      
53      public static Thread getThreadByName(String name) {
54          for (Thread t: Thread.getAllStackTraces().keySet()) {
55              if (name.equals(t.getName())) {
56                  return t;
57              }
58          }
59          
60          return null;
61      }
62      
63      public static List<Thread> getThreadsByRegexName(String regex) {
64          List<Thread> result = Lists.newArrayList();
65          
66          for (Thread t: Thread.getAllStackTraces().keySet()) {
67              String threadName = t.getName();
68              if (threadName.matches(regex)) {
69                  result.add(t);
70              }
71          }
72          
73          return result;
74      }
75  
76      public static void stopThread(Thread t) {
77          Assert.notNull(t);
78          
79          if (!t.isInterrupted()) {
80              t.interrupt();
81          }
82      }
83      
84  }