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