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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.