Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source
   * Copyright 2008, JBoss Inc., and individual contributors as indicated
   * by the @authors tag. See the copyright.txt in the distribution for a
   * full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 
 package org.jboss.threads.metadata;
 
 import java.util.List;
 import java.util.Map;
 import static java.lang.Math.max;
 
 
 @JBossXmlSchema(namespace = "urn:jboss:threads:1.0", elementFormDefault = .)
 @XmlRootElement(name = "threads")
 @XmlType(name = "threads")
 public final class ThreadsMetaData implements BeanMetaDataFactory {
     private static final class StringEntry implements Map.Entry<StringString> {
         private final String key;
         private final String value;
 
         private StringEntry(final String keyfinal String value) {
             this. = key;
             this. = value;
         }
 
         public String getKey() {
             return ;
         }
 
         public String getValue() {
             return ;
         }
 
         public String setValue(final String value) {
             throw new UnsupportedOperationException();
         }
     }
 
     private static StringEntry entry(final String keyfinal String value) {
         return new StringEntry(keyvalue);
     }
 
     private static Map<StringStringstringMap(StringEntry... entries) {
        final HashMap<StringStringhashMap = new HashMap<StringString>(entries.length);
        for (Map.Entry<StringStringe : entries) {
            hashMap.put(e.getKey(), e.getValue());
        }
        return Collections.unmodifiableMap(hashMap);
    }
    private static final Map<StringStringUNIT_NICK_NAMES = stringMap(
            entry("S""SECONDS"),
            entry("SEC""SECONDS"),
            entry("M""MINUTES"),
            entry("MIN""MINUTES"),
            entry("MS""MILLISECONDS"),
            entry("NS""NANOSECONDS"),
            entry("H""HOURS"),
            entry("D""DAYS"),
            entry("MON""MONTHS"),
            entry("W""WEEKS")
    );
        return ;
    }
    @XmlElement(name = "thread-group")
    public void setThreadGroups(final List<ThreadGroupMetaDatathreadGroups) {
        this. = threadGroups;
    }
        return ;
    }
    @XmlElement(name = "thread-factory")
    public void setThreadFactories(final List<ThreadFactoryMetaDatathreadFactories) {
        this. = threadFactories;
    }
        return ;
    }
    @XmlElement(name = "thread-pool-executor")
    public void setThreadPoolExecutors(final List<ThreadPoolExecutorMetaDatathreadPoolExecutors) {
        this. = threadPoolExecutors;
    }
        return ;
    }
    @XmlElement(name = "direct-executor")
    public void setDirectExecutors(final List<DirectExecutorMetaDatadirectExecutors) {
        this. = directExecutors;
    }
        return ;
    }
    @XmlElement(name = "notating-executor")
    public void setNotatingExecutors(final List<NotatingExecutorMetaDatanotatingExecutors) {
        this. = notatingExecutors;
    }
        return ;
    }
    @XmlElement(name = "scheduled-thread-pool-executor")
    public void setScheduledThreadPoolExecutors(final List<ScheduledThreadPoolExecutorMetaDatascheduledThreadPoolExecutors) {
        this. = scheduledThreadPoolExecutors;
    }
    public List<BeanMetaDatagetBeans() {
        List<BeanMetaDatabeanMetaDataList = new ArrayList<BeanMetaData>();
        for (ThreadGroupMetaData metaData : ) {
            final String name = metaData.getName();
            final BeanMetaDataBuilder builder = BeanMetaDataBuilder.createBuilder(nameThreadGroup.class.getName());
            builder.setMode(.);
            final String parent = metaData.getParent();
            if (parent != null && parent.length() > 0) {
                builder.addConstructorParameter(ThreadGroup.class.getName(), builder.createInject(parent));
            }
            builder.addConstructorParameter(String.class.getName(), builder.createValue(name));
            if (metaData.isDaemon() != null) {
                builder.addPropertyMetaData("daemon"builder.createValue(metaData.isDaemon()));
            }
            final Integer maxPriorityMeta = metaData.getMaxPriority();
            if (maxPriorityMeta != null) {
                builder.addPropertyMetaData("maxPriority"builder.createValue(maxPriorityMeta));
            }
            builder.ignoreStop();
            builder.ignoreDestroy();
            beanMetaDataList.add(builder.getBeanMetaData());
        }
        for (ThreadFactoryMetaData metaData : ) {
            final String name = metaData.getName();
            final BeanMetaDataBuilder builder = BeanMetaDataBuilder.createBuilder(nameJBossThreadFactory.class.getName());
            builder.setMode(.);
            final String group = metaData.getGroup();
            builder.addConstructorParameter(ThreadGroup.class.getName(), group == null ? builder.createNull() : builder.createInject(group));
            final Boolean daemon = metaData.getDaemon();
            builder.addConstructorParameter(Boolean.class.getName(), daemon == null ? builder.createNull() : builder.createValue(daemon));
            final Integer priorityMeta = metaData.getInitialPriority();
            final Integer actualPriorityMeta;
            if (priorityMeta != null) {
                actualPriorityMeta = priorityMeta;
            } else {
                actualPriorityMeta = null;
            }
            builder.addConstructorParameter(Integer.class.getName(), actualPriorityMeta == null ? builder.createNull() : builder.createValue(actualPriorityMeta));
            builder.addConstructorParameter(String.class.getName(), builder.createValue(metaData.getThreadNamePattern()));
            final List<ValueMetaDatainterruptHandlers = builder.createArray(InterruptHandler[].class.getName(), InterruptHandler.class.getName());
            for (InterruptHandlerRefMetaData ihmd : metaData.getInterruptHandlers()) {
                interruptHandlers.add(builder.createInject(ihmd.getName()));
            }
            builder.addConstructorParameter(InterruptHandler[].class.getName(), (ValueMetaDatainterruptHandlers);
            final ExceptionHandlerRefMetaData ehmd = metaData.getExceptionHandler();
            builder.addConstructorParameter(Thread.UncaughtExceptionHandler.class.getName(), ehmd == null ? builder.createNull() : builder.createInject(ehmd.getName()));
            final Long stackSize = metaData.getStackSize();
            builder.addConstructorParameter(Long.class.getName(), stackSize == null ? builder.createNull() : builder.createValue(stackSize));
            beanMetaDataList.add(builder.getBeanMetaData());
        }
        for (ThreadPoolExecutorMetaData metaData : ) {
            final String name = metaData.getName();
            final PoolSizeMetaData corePoolSizeMetaData = metaData.getCorePoolSize();
            final int corePoolSize;
            if (corePoolSizeMetaData == null) {
                corePoolSize = 0;
            } else {
                corePoolSize = max(calcPoolSize(corePoolSizeMetaData), 0);
            }
            final PoolSizeMetaData maxPoolSizeMetaData = metaData.getMaxPoolSize();
            final int maxPoolSize;
            if (maxPoolSizeMetaData == null) {
                maxPoolSize = max(corePoolSize, 1);
            } else {
                maxPoolSize = max(calcPoolSize(maxPoolSizeMetaData), max(1, corePoolSize));
            }
            final TimeMetaData timeMetaData = metaData.getKeepAliveTime();
            final long time;
            final TimeUnit unit;
            if (timeMetaData == null) {
                time = .;
                unit = .;
            } else {
                time = max(0L, timeMetaData.getTime());
                final String unitName = timeMetaData.getUnit();
                if (unitName == null) {
                    unit = .;
                } else {
                    final String upperUnitName = unitName.toUpperCase();
                    if (.containsKey(upperUnitName)) {
                        unit = TimeUnit.valueOf(.get(upperUnitName));
                    } else {
                        unit = TimeUnit.valueOf(upperUnitName);
                    }
                }
            }
            final String threadFactory = metaData.getThreadFactory();
            if (threadFactory == null) {
                throw new IllegalArgumentException("threadFactory is not defined");
            }
            final Integer queueLength = metaData.getQueueLength();
            final RejectPolicyMetaData rejectPolicyMetaData = metaData.getRejectPolicyMetaData();
            final String policyName = rejectPolicyMetaData == null ? "block" : rejectPolicyMetaData.getName();
            final BeanMetaDataBuilder executorBuilder;
            // here is where we decide which thread pool implementation to use
            // right now, our criteria is simple - if blocking is desired or if core threads can time out, use the queue executor instead
            if (metaData.isAllowCoreTimeout() || "block".equals(policyName)) {
                // use SimpleQueueExecutor
                executorBuilder = BeanMetaDataBuilder.createBuilder(SimpleQueueExecutor.class.getName());
                final RejectionPolicy rejectionPolicy;
                final ValueMetaData handoffExecutorValue;
                if ("abort".equals(policyName)) {
                    rejectionPolicy = .;
                    handoffExecutorValue = executorBuilder.createNull();
                } else if ("block".equals(policyName)) {
                    rejectionPolicy = .;
                    handoffExecutorValue = executorBuilder.createNull();
                } else if ("caller-runs".equals(policyName)) {
                    rejectionPolicy = .;
                    handoffExecutorValue = executorBuilder.createValue(JBossExecutors.directExecutor());
                } else if ("discard".equals(policyName)) {
                    rejectionPolicy = .;
                    handoffExecutorValue = executorBuilder.createNull();
                } else if ("discard-oldest".equals(policyName)) {
                    rejectionPolicy = .;
                    handoffExecutorValue = executorBuilder.createNull();
                } else if ("handoff".equals(policyName)) {
                    rejectionPolicy = .;
                    handoffExecutorValue = executorBuilder.createInject(rejectPolicyMetaData.getExecutorName());
                } else {
                    throw new IllegalStateException();
                }
                final Queue<Runnablequeue;
                if (queueLength == null) {
                    queue = new LinkedList<Runnable>();
                } else {
                    queue = new ArrayQueue<Runnable>(queueLength.intValue());
                }
                executorBuilder.addConstructorParameter(String.class.getName(), name);
                executorBuilder.addConstructorParameter("int", Integer.valueOf(corePoolSize));
                executorBuilder.addConstructorParameter("int", Integer.valueOf(maxPoolSize));
                executorBuilder.addConstructorParameter("long", Long.valueOf(time));
                executorBuilder.addConstructorParameter(TimeUnit.class.getName(), unit);
                executorBuilder.addConstructorParameter(Queue.class.getName(), executorBuilder.createValue(queue));
                executorBuilder.addConstructorParameter(ThreadFactory.class.getName(), executorBuilder.createInject(threadFactory));
                executorBuilder.addConstructorParameter(RejectionPolicy.class.getName(), rejectionPolicy);
                executorBuilder.addConstructorParameter(Executor.class.getName(), handoffExecutorValue);
                if (metaData.isAllowCoreTimeout()) {
                    executorBuilder.addPropertyMetaData("allowCoreTimeout".);
                }
            } else {
                // use ThreadPoolExecutor
                executorBuilder = BeanMetaDataBuilder.createBuilder(JBossThreadPoolExecutor.class.getName());
                final ValueMetaData policyValue;
                if ("abort".equals(policyName)) {
                    policyValue = executorBuilder.createValue(JBossExecutors.abortPolicy());
                } else if ("block".equals(policyName)) {
                    throw new IllegalStateException();
                } else if ("caller-runs".equals(policyName)) {
                    policyValue = executorBuilder.createValue(JBossExecutors.callerRunsPolicy());
                } else if ("discard".equals(policyName)) {
                    policyValue = executorBuilder.createValue(JBossExecutors.discardPolicy());
                } else if ("discard-oldest".equals(policyName)) {
                    policyValue = executorBuilder.createValue(JBossExecutors.discardOldestPolicy());
                } else if ("handoff".equals(policyName)) {
                    final BeanMetaDataBuilder policyBuilder = BeanMetaDataBuilder.createBuilder(RejectedExecutionHandler.class.getName());
                    policyBuilder.setFactoryClass(JBossExecutors.class.getName());
                    policyBuilder.setFactoryMethod("handoffPolicy");
                    policyBuilder.addConstructorParameter(Executor.class.getName(), policyBuilder.createInject(rejectPolicyMetaData.getExecutorName()));
                    policyValue = policyBuilder.getBeanMetaData();
                } else {
                    throw new IllegalStateException();
                }
                final BlockingQueue<Runnablequeue;
                if (queueLength == null) {
                    // todo: try LinkedTransferQueue
                    queue = new LinkedBlockingQueue<Runnable>();
                } else {
                    queue = new ArrayBlockingQueue<Runnable>(queueLength.intValue());
                }
                executorBuilder.addConstructorParameter(String.class.getName(), name);
                executorBuilder.addConstructorParameter("int", Integer.valueOf(corePoolSize));
                executorBuilder.addConstructorParameter("int", Integer.valueOf(maxPoolSize));
                executorBuilder.addConstructorParameter("long", Long.valueOf(time));
                executorBuilder.addConstructorParameter(TimeUnit.class.getName(), unit);
                executorBuilder.addConstructorParameter(BlockingQueue.class.getName(), executorBuilder.createValue(queue));
                executorBuilder.addConstructorParameter(ThreadFactory.class.getName(), executorBuilder.createInject(threadFactory));
                executorBuilder.addConstructorParameter(RejectedExecutionHandler.class.getName(), policyValue);
            }
            executorBuilder.addAnnotation(new JMX() {
                public Class<?> exposedInterface() {
                    return ThreadPoolExecutorMBean.class;
                }
                public String name() {
                    return "jboss.threads:service=ThreadPoolExecutor,name=" + name;
                }
                public boolean registerDirectly() {
                    return false;
                }
                public Class<? extends AnnotationannotationType() {
                    return JMX.class;
                }
            });
            executorBuilder.setMode(.);
//            final BeanMetaDataBuilder builder = BeanMetaDataBuilder.createBuilder(name, ExecutorService.class.getName());
//            builder.setFactoryClass(JBossExecutors.class.getName());
//            builder.setFactoryMethod("protectedExecutorService");
//            builder.addConstructorParameter(Executor.class.getName(), executorBuilder.getBeanMetaData());
//            builder.setMode(ControllerMode.ON_DEMAND);
//            beanMetaDataList.add(builder.getBeanMetaData());
            executorBuilder.setName(name);
            beanMetaDataList.add(executorBuilder.getBeanMetaData());
        }
        for (DirectExecutorMetaData metaData : ) {
            final String name = metaData.getName();
            final BeanMetaDataBuilder builder = BeanMetaDataBuilder.createBuilder(nameExecutorService.class.getName());
            builder.setFactoryClass(JBossExecutors.class.getName());
            builder.setFactoryMethod("directExecutorService");
            builder.setMode(.);
            beanMetaDataList.add(builder.getBeanMetaData());
        }
        for (NotatingExecutorMetaData metaData : ) {
            final String name = metaData.getName();
            final BeanMetaDataBuilder builder = BeanMetaDataBuilder.createBuilder(nameDirectExecutor.class.getName());
            builder.setMode(.);
            builder.setFactoryClass(JBossExecutors.class.getName());
            builder.setFactoryMethod("notatingExecutor");
            builder.addConstructorParameter(Executor.class.getName(), builder.createInject(metaData.getParent()));
            builder.addConstructorParameter(String.class.getName(), metaData.getNote());
            beanMetaDataList.add(builder.getBeanMetaData());
        }
            final String name = metaData.getName();
            final BeanMetaDataBuilder builder = BeanMetaDataBuilder.createBuilder(nameScheduledThreadPoolExecutor.class.getName());
            builder.setMode(.);
            final PoolSizeMetaData poolSizeMetaData = metaData.getPoolSize();
            final int size;
            if (poolSizeMetaData != null) {
                size = max(1, calcPoolSize(poolSizeMetaData));
            } else {
                size = 1;
            }
            builder.addConstructorParameter("int", Integer.valueOf(size));
            final String threadFactoryName = metaData.getThreadFactory();
            if (threadFactoryName != null) {
                builder.addConstructorParameter(ThreadFactory.class.getName(), builder.createInject(threadFactoryName));
            }
            beanMetaDataList.add(builder.getBeanMetaData());
        }
        return beanMetaDataList;
    }
    private static int calcPoolSize(PoolSizeMetaData poolSizeMetaData) {
        float count = poolSizeMetaData.getCount();
        float perCpu = poolSizeMetaData.getPerCpu();
        if (Float.isNaN(count) || Float.isInfinite(count) || count < 0.0f) {
            count = 0.0f;
        }
        if (Float.isNaN(perCpu) || Float.isInfinite(perCpu) || perCpu < 0.0f) {
            perCpu = 0.0f;
        }
        return Math.round(count + ((float) Runtime.getRuntime().availableProcessors()) * perCpu);
    }
New to GrepCode? Check out our FAQ X