f5c395915114404766d3c60094b48198988d27a3
[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.RejectedExecutionHandler;
20 import java.util.concurrent.ThreadFactory;
21 import java.util.concurrent.ThreadPoolExecutor;
22 import java.util.concurrent.TimeUnit;
23 import javassist.ClassPool;
24 import org.apache.commons.lang3.StringUtils;
25 import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 public class SingletonHolder {
30     private static final Logger logger = LoggerFactory.getLogger(SingletonHolder.class);
31
32     public static final ClassPool CLASS_POOL = ClassPool.getDefault();
33     public static final JavassistUtils JAVASSIST = JavassistUtils.forClassPool(CLASS_POOL);
34     public static final org.opendaylight.controller.sal.binding.codegen.impl.DefaultRuntimeCodeGenerator RPC_GENERATOR_IMPL = new org.opendaylight.controller.sal.binding.codegen.impl.DefaultRuntimeCodeGenerator(
35             CLASS_POOL);
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             final 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 (final NumberFormatException e) {
63                     logger.warn("Cannot parse {} as set by {}, using default {}", queueValue,
64                             NOTIFICATION_QUEUE_SIZE_PROPERTY, queueSize);
65                 }
66             }
67
68             // Overriding the queue:
69             // ThreadPoolExecutor would not create new threads if the queue is not full, thus adding
70             // occurs in RejectedExecutionHandler.
71             // This impl saturates threadpool first, then queue. When both are full caller will get blocked.
72             final BlockingQueue<Runnable> delegate = new LinkedBlockingQueue<>(queueSize);
73             final BlockingQueue<Runnable> queue = new ForwardingBlockingQueue<Runnable>() {
74                 @Override
75                 protected BlockingQueue<Runnable> delegate() {
76                     return delegate;
77                 }
78
79                 @Override
80                 public boolean offer(final Runnable r) {
81                     // ThreadPoolExecutor will spawn a new thread after core size is reached only
82                     // if the queue.offer returns false.
83                     return false;
84                 }
85             };
86
87             final ThreadFactory factory = new ThreadFactoryBuilder()
88             .setDaemon(true)
89             .setNameFormat("md-sal-binding-notification-%d")
90             .build();
91
92             final ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_NOTIFICATION_THREADS, MAX_NOTIFICATION_THREADS,
93                     NOTIFICATION_THREAD_LIFE, TimeUnit.SECONDS, queue, factory,
94                     new RejectedExecutionHandler() {
95                 // if the max threads are met, then it will raise a rejectedExecution. We then push to the queue.
96                 @Override
97                 public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
98                     try {
99                         executor.getQueue().put(r);
100                     } catch (final InterruptedException e) {
101                         throw new RejectedExecutionException("Interrupted while waiting on the queue", e);
102                     }
103                 }
104             });
105
106             NOTIFICATION_EXECUTOR = MoreExecutors.listeningDecorator(executor);
107         }
108
109         return NOTIFICATION_EXECUTOR;
110     }
111
112     /**
113      * @deprecated This method is only used from configuration modules and thus callers of it
114      *             should use service injection to make the executor configurable.
115      */
116     @Deprecated
117     public static synchronized ListeningExecutorService getDefaultCommitExecutor() {
118         if (COMMIT_EXECUTOR == null) {
119             final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).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 ExecutorService getDefaultChangeEventExecutor() {
135         if (CHANGE_EVENT_EXECUTOR == null) {
136             final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("md-sal-binding-change-%d").build();
137             /*
138              * FIXME: this used to be newCacheThreadPool(), but MD-SAL does not have transaction
139              *        ordering guarantees, which means that using a concurrent threadpool results
140              *        in application data being committed in random order, potentially resulting
141              *        in inconsistent data being present. Once proper primitives are introduced,
142              *        concurrency can be reintroduced.
143              */
144             final ExecutorService executor = Executors.newSingleThreadExecutor(factory);
145             CHANGE_EVENT_EXECUTOR  = MoreExecutors.listeningDecorator(executor);
146         }
147
148         return CHANGE_EVENT_EXECUTOR;
149     }
150 }