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