13312b51b3a6606d84f2c710ec85aa74c16e2b4d
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / codegen / impl / SingletonHolder.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.sal.binding.codegen.impl;
9
10 import com.google.common.util.concurrent.ForwardingBlockingQueue;
11 import com.google.common.util.concurrent.ListeningExecutorService;
12 import com.google.common.util.concurrent.MoreExecutors;
13 import com.google.common.util.concurrent.ThreadFactoryBuilder;
14 import java.util.concurrent.BlockingQueue;
15 import java.util.concurrent.ExecutorService;
16 import java.util.concurrent.Executors;
17 import java.util.concurrent.LinkedBlockingQueue;
18 import java.util.concurrent.RejectedExecutionException;
19 import java.util.concurrent.ThreadFactory;
20 import java.util.concurrent.ThreadPoolExecutor;
21 import java.util.concurrent.TimeUnit;
22 import javassist.ClassPool;
23 import org.apache.commons.lang3.StringUtils;
24 import org.opendaylight.mdsal.binding.generator.util.JavassistUtils;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 public final class SingletonHolder {
29     private static final Logger LOG = LoggerFactory.getLogger(SingletonHolder.class);
30
31     public static final ClassPool CLASS_POOL = ClassPool.getDefault();
32     public static final JavassistUtils JAVASSIST = JavassistUtils.forClassPool(CLASS_POOL);
33
34     public static final int CORE_NOTIFICATION_THREADS = 4;
35     public static final int MAX_NOTIFICATION_THREADS = 32;
36     // block caller thread after MAX_NOTIFICATION_THREADS + MAX_NOTIFICATION_QUEUE_SIZE pending notifications
37     public static final int MAX_NOTIFICATION_QUEUE_SIZE = 1000;
38     public static final int NOTIFICATION_THREAD_LIFE = 15;
39     private static final String NOTIFICATION_QUEUE_SIZE_PROPERTY = "mdsal.notificationqueue.size";
40
41     private static ListeningExecutorService NOTIFICATION_EXECUTOR = null;
42     private static ListeningExecutorService COMMIT_EXECUTOR = null;
43     private static ListeningExecutorService CHANGE_EVENT_EXECUTOR = null;
44
45     private SingletonHolder() {
46     }
47
48     /**
49      * Deprecated.
50      *
51      * @deprecated This method is only used from configuration modules and thus callers of it
52      *             should use service injection to make the executor configurable.
53      */
54     @Deprecated
55     public static synchronized ListeningExecutorService getDefaultNotificationExecutor() {
56
57         if (NOTIFICATION_EXECUTOR == null) {
58             int queueSize = MAX_NOTIFICATION_QUEUE_SIZE;
59             final String queueValue = System.getProperty(NOTIFICATION_QUEUE_SIZE_PROPERTY);
60             if (StringUtils.isNotBlank(queueValue)) {
61                 try {
62                     queueSize = Integer.parseInt(queueValue);
63                     LOG.trace("Queue size was set to {}", queueSize);
64                 } catch (final NumberFormatException e) {
65                     LOG.warn("Cannot parse {} as set by {}, using default {}", queueValue,
66                             NOTIFICATION_QUEUE_SIZE_PROPERTY, queueSize);
67                 }
68             }
69
70             // Overriding the queue:
71             // ThreadPoolExecutor would not create new threads if the queue is not full, thus adding
72             // occurs in RejectedExecutionHandler.
73             // This impl saturates threadpool first, then queue. When both are full caller will get blocked.
74             final BlockingQueue<Runnable> delegate = new LinkedBlockingQueue<>(queueSize);
75             final BlockingQueue<Runnable> queue = new ForwardingBlockingQueue<Runnable>() {
76                 @Override
77                 protected BlockingQueue<Runnable> delegate() {
78                     return delegate;
79                 }
80
81                 @Override
82                 public boolean offer(final Runnable runnrunnableable) {
83                     // ThreadPoolExecutor will spawn a new thread after core size is reached only
84                     // if the queue.offer returns false.
85                     return false;
86                 }
87             };
88
89             final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true)
90                     .setNameFormat("md-sal-binding-notification-%d").build();
91
92             final ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_NOTIFICATION_THREADS,
93                 MAX_NOTIFICATION_THREADS, NOTIFICATION_THREAD_LIFE, TimeUnit.SECONDS, queue, factory,
94                 // if the max threads are met, then it will raise a rejectedExecution. We then push to the queue.
95                 (runnable, executor1) -> {
96                     try {
97                         executor1.getQueue().put(runnable);
98                     } catch (final InterruptedException e) {
99                         throw new RejectedExecutionException("Interrupted while waiting on the queue", e);
100                     }
101                 });
102
103             NOTIFICATION_EXECUTOR = MoreExecutors.listeningDecorator(executor);
104         }
105
106         return NOTIFICATION_EXECUTOR;
107     }
108
109     /**
110      * Deprecated.
111      *
112      * @deprecated This method is only used from configuration modules and thus callers of it
113      *             should use service injection to make the executor configurable.
114      */
115     @Deprecated
116     public static synchronized ListeningExecutorService getDefaultCommitExecutor() {
117         if (COMMIT_EXECUTOR == null) {
118             final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true)
119                     .setNameFormat("md-sal-binding-commit-%d").build();
120             /*
121              * FIXME: this used to be newCacheThreadPool(), but MD-SAL does not have transaction
122              *        ordering guarantees, which means that using a concurrent threadpool results
123              *        in application data being committed in random order, potentially resulting
124              *        in inconsistent data being present. Once proper primitives are introduced,
125              *        concurrency can be reintroduced.
126              */
127             final ExecutorService executor = Executors.newSingleThreadExecutor(factory);
128             COMMIT_EXECUTOR = MoreExecutors.listeningDecorator(executor);
129         }
130
131         return COMMIT_EXECUTOR;
132     }
133
134     public static synchronized ExecutorService getDefaultChangeEventExecutor() {
135         if (CHANGE_EVENT_EXECUTOR == null) {
136             final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true)
137                     .setNameFormat("md-sal-binding-change-%d").build();
138             /*
139              * FIXME: this used to be newCacheThreadPool(), but MD-SAL does not have transaction
140              *        ordering guarantees, which means that using a concurrent threadpool results
141              *        in application data being committed in random order, potentially resulting
142              *        in inconsistent data being present. Once proper primitives are introduced,
143              *        concurrency can be reintroduced.
144              */
145             final ExecutorService executor = Executors.newSingleThreadExecutor(factory);
146             CHANGE_EVENT_EXECUTOR  = MoreExecutors.listeningDecorator(executor);
147         }
148
149         return CHANGE_EVENT_EXECUTOR;
150     }
151 }