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