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