8621638460758f0518f1063b69636d9a7bfef6d3
[sdc.git] /
1 /*
2  * Copyright © 2016-2017 European Support Limited
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 package org.openecomp.sdc.logging.api.context;
18
19 import org.openecomp.sdc.logging.api.BaseFactory;
20
21 /**
22  * <p>Should be used to propagate a diagnostic context (for instance <a
23  * href="http://www.slf4j.org/manual.html#mdc">MDC</a>) to other threads.</p>
24  * <p>Applicable when creating a child thread directly, or submitting tasks for potentially
25  * postponed execution via an <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html">Executor</a>
26  * (including any of the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html">executor
27  * services</a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html">ForkJoinPool</a>).</p>
28  * <p>The service used by this factory must implement {@link ContextPropagationService}.</p>
29  *
30  * @author evitaliy
31  * @see ContextPropagationService
32  * @since 12/09/2016.
33  */
34 @SuppressWarnings("ThrowableInstanceNeverThrown")
35 public class TaskFactory extends BaseFactory {
36
37   private static final ContextPropagationService SERVICE;
38   private static final RuntimeException ERROR;
39
40   static {
41
42     ContextPropagationService service = null;
43     RuntimeException error = null;
44
45     try {
46       service = locateService(ContextPropagationService.class);
47     } catch (Exception ex) {
48       error = new RuntimeException("Failed to instantiate task factory", ex);
49     }
50
51     SERVICE = service;
52     ERROR = error;
53   }
54
55   /**
56    * Modify a task so that a diagnostic context is propagated to the thread when the task runs. Done
57    * in a logging-framework specific way.
58    *
59    * @param task any Runnable that will run in a thread
60    * @return modified (wrapped) original task that runs the same business logic, but also takes care
61    * of copying the diagnostic context for logging
62    */
63   public static Runnable create(Runnable task) {
64
65     if (SERVICE == null) {
66       throw ERROR;
67     }
68
69     return SERVICE.create(task);
70   }
71 }