Example usage for java.lang Thread setPriority

List of usage examples for java.lang Thread setPriority

Introduction

In this page you can find the example usage for java.lang Thread setPriority.

Prototype

public final void setPriority(int newPriority) 

Source Link

Document

Changes the priority of this thread.

Usage

From source file:net.sourceforge.subsonic.service.SearchService.java

/**
 * Generates the search index.  If the index already exists it will be
 * overwritten.  The index is created asynchronously, i.e., this method returns
 * before the index is created./*from w w w.ja va 2 s. co  m*/
 */
public synchronized void createIndex() {
    if (isIndexBeingCreated()) {
        return;
    }
    creatingIndex = true;

    Thread thread = new Thread("Search Index Generator") {
        @Override
        public void run() {
            doCreateIndex();
        }
    };

    thread.setPriority(Thread.MIN_PRIORITY);
    thread.start();
}

From source file:org.apache.xml.security.stax.impl.processor.input.AbstractDecryptInputProcessor.java

private XMLSecEvent processEvent(InputProcessorChain inputProcessorChain, boolean isSecurityHeaderEvent)
        throws XMLStreamException, XMLSecurityException {

    if (!tmpXmlEventList.isEmpty()) {
        return tmpXmlEventList.pollLast();
    }/* w w w .  j  a v a  2  s  .  c o m*/

    XMLSecEvent xmlSecEvent = isSecurityHeaderEvent ? inputProcessorChain.processHeaderEvent()
            : inputProcessorChain.processEvent();

    boolean encryptedHeader = false;

    if (xmlSecEvent.getEventType() == XMLStreamConstants.START_ELEMENT) {
        XMLSecStartElement xmlSecStartElement = xmlSecEvent.asStartElement();

        //buffer the events until the EncryptedData Element appears and discard it if we found the reference inside it
        //otherwise replay it
        if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_wsse11_EncryptedHeader)) {
            xmlSecEvent = readAndBufferEncryptedHeader(inputProcessorChain, isSecurityHeaderEvent, xmlSecEvent);
            xmlSecStartElement = xmlSecEvent.asStartElement();
            encryptedHeader = true;
        }

        //check if the current start-element has the name EncryptedData and an Id attribute
        if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData)) {
            ReferenceType referenceType = null;
            if (references != null) {
                referenceType = matchesReferenceId(xmlSecStartElement);
                if (referenceType == null) {
                    //if the events were not for us (no matching reference-id the we have to replay the EncryptedHeader elements)
                    if (!tmpXmlEventList.isEmpty()) {
                        return tmpXmlEventList.pollLast();
                    }
                    return xmlSecEvent;
                }
                //duplicate id's are forbidden
                if (processedReferences.contains(referenceType)) {
                    throw new XMLSecurityException("signature.Verification.MultipleIDs");
                }

                processedReferences.add(referenceType);
            }
            tmpXmlEventList.clear();

            //the following logic reads the encryptedData structure and doesn't pass them further
            //through the chain
            InputProcessorChain subInputProcessorChain = inputProcessorChain.createSubChain(this);

            EncryptedDataType encryptedDataType = parseEncryptedDataStructure(isSecurityHeaderEvent,
                    xmlSecEvent, subInputProcessorChain);
            if (encryptedDataType.getId() == null) {
                encryptedDataType.setId(IDGenerator.generateID(null));
            }

            InboundSecurityToken inboundSecurityToken = getSecurityToken(inputProcessorChain,
                    xmlSecStartElement, encryptedDataType);
            handleSecurityToken(inboundSecurityToken, inputProcessorChain.getSecurityContext(),
                    encryptedDataType);

            final String algorithmURI = encryptedDataType.getEncryptionMethod().getAlgorithm();
            final int ivLength = JCEAlgorithmMapper.getIVLengthFromURI(algorithmURI) / 8;
            Cipher symCipher = getCipher(algorithmURI);

            if (encryptedDataType.getCipherData().getCipherReference() != null) {
                handleCipherReference(inputProcessorChain, encryptedDataType, symCipher, inboundSecurityToken);
                subInputProcessorChain.reset();
                return isSecurityHeaderEvent ? subInputProcessorChain.processHeaderEvent()
                        : subInputProcessorChain.processEvent();
            }

            //create a new Thread for streaming decryption
            DecryptionThread decryptionThread = new DecryptionThread(subInputProcessorChain,
                    isSecurityHeaderEvent);
            Key decryptionKey = inboundSecurityToken.getSecretKey(algorithmURI, XMLSecurityConstants.Enc,
                    encryptedDataType.getId());
            decryptionKey = XMLSecurityUtils.prepareSecretKey(algorithmURI, decryptionKey.getEncoded());
            decryptionThread.setSecretKey(decryptionKey);
            decryptionThread.setSymmetricCipher(symCipher);
            decryptionThread.setIvLength(ivLength);
            XMLSecStartElement parentXMLSecStartElement = xmlSecStartElement.getParentXMLSecStartElement();
            if (encryptedHeader) {
                parentXMLSecStartElement = parentXMLSecStartElement.getParentXMLSecStartElement();
            }
            AbstractDecryptedEventReaderInputProcessor decryptedEventReaderInputProcessor = newDecryptedEventReaderInputProcessor(
                    encryptedHeader, parentXMLSecStartElement, encryptedDataType, inboundSecurityToken,
                    inputProcessorChain.getSecurityContext());

            //add the new created EventReader processor to the chain.
            inputProcessorChain.addProcessor(decryptedEventReaderInputProcessor);

            inputProcessorChain.getDocumentContext().setIsInEncryptedContent(
                    inputProcessorChain.getProcessors().indexOf(decryptedEventReaderInputProcessor),
                    decryptedEventReaderInputProcessor);

            //fire here only ContentEncryptedElementEvents
            //the other ones will be fired later, because we don't know the encrypted element name yet
            //important: this must occur after setIsInEncryptedContent!
            if (SecurePart.Modifier.Content.getModifier().equals(encryptedDataType.getType())) {
                handleEncryptedContent(inputProcessorChain, xmlSecStartElement.getParentXMLSecStartElement(),
                        inboundSecurityToken, encryptedDataType);
            }

            Thread thread = new Thread(decryptionThread);
            thread.setPriority(Thread.NORM_PRIORITY + 1);
            thread.setName("decryption thread");
            //when an exception in the decryption thread occurs, we want to forward them:
            thread.setUncaughtExceptionHandler(decryptedEventReaderInputProcessor);

            decryptedEventReaderInputProcessor.setDecryptionThread(thread);

            //we have to start the thread before we call decryptionThread.getPipedInputStream().
            //Otherwise we will end in a deadlock, because the StAX reader expects already data.
            //@See some lines below:
            log.debug("Starting decryption thread");
            thread.start();

            InputStream prologInputStream;
            InputStream epilogInputStream;
            try {
                prologInputStream = writeWrapperStartElement(xmlSecStartElement);
                epilogInputStream = writeWrapperEndElement();
            } catch (UnsupportedEncodingException e) {
                throw new XMLSecurityException(e);
            } catch (IOException e) {
                throw new XMLSecurityException(e);
            }

            InputStream decryptInputStream = decryptionThread.getPipedInputStream();
            decryptInputStream = applyTransforms(referenceType, decryptInputStream);

            //spec says (4.2): "The cleartext octet sequence obtained in step 3 is
            //interpreted as UTF-8 encoded character data."
            XMLStreamReader xmlStreamReader = inputProcessorChain.getSecurityContext()
                    .<XMLInputFactory>get(XMLSecurityConstants.XMLINPUTFACTORY).createXMLStreamReader(
                            new MultiInputStream(prologInputStream, decryptInputStream, epilogInputStream),
                            "UTF-8");

            //forward to wrapper element
            forwardToWrapperElement(xmlStreamReader);

            decryptedEventReaderInputProcessor.setXmlStreamReader(xmlStreamReader);

            if (isSecurityHeaderEvent) {
                return decryptedEventReaderInputProcessor.processNextHeaderEvent(inputProcessorChain);
            } else {
                return decryptedEventReaderInputProcessor.processNextEvent(inputProcessorChain);
            }
        }
    }
    return xmlSecEvent;
}

From source file:org.languagetool.gui.LanguageToolSupport.java

private void init() {
    try {//from   w ww. ja va 2  s.c  o m
        config = new Configuration(new File(System.getProperty("user.home")), CONFIG_FILE, null);
    } catch (IOException ex) {
        throw new RuntimeException("Could not load configuration", ex);
    }

    Language defaultLanguage = config.getLanguage();
    if (defaultLanguage == null) {
        defaultLanguage = Languages.getLanguageForLocale(Locale.getDefault());
    }

    /**
     * Warm-up: we have a lot of lazy init in LT, which causes the first check to
     * be very slow (several seconds) for languages with a lot of data and a lot of
     * rules. We just assume that the default language is the language that the user
     * often uses and init the LT object for that now, not just when it's first used.
     * This makes the first check feel much faster:
     */
    reloadLanguageTool(defaultLanguage);

    checkExecutor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            t.setPriority(Thread.MIN_PRIORITY);
            t.setName(t.getName() + "-lt-background");
            return t;
        }
    });

    check = new AtomicInteger(0);

    this.textComponent.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            recalculateSpans(e.getOffset(), e.getLength(), false);
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            recalculateSpans(e.getOffset(), e.getLength(), true);
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }
    });

    mouseListener = new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent me) {
        }

        @Override
        public void mousePressed(MouseEvent me) {
            if (me.isPopupTrigger()) {
                showPopup(me);
            }
        }

        @Override
        public void mouseReleased(MouseEvent me) {
            if (me.isPopupTrigger()) {
                showPopup(me);
            }
        }

        @Override
        public void mouseEntered(MouseEvent me) {
        }

        @Override
        public void mouseExited(MouseEvent me) {
        }
    };
    this.textComponent.addMouseListener(mouseListener);

    actionListener = e -> _actionPerformed(e);

    mustDetectLanguage = config.getAutoDetect();
    if (!this.textComponent.getText().isEmpty() && backgroundCheckEnabled) {
        checkImmediately(null);
    }
}

From source file:Animator.java

/**
 * Run the animation. This method is called by class Thread.
 * // w ww. ja v  a2  s .com
 * @see java.lang.Thread
 */
public void run() {
    Thread me = Thread.currentThread();
    URL badURL;

    me.setPriority(Thread.MIN_PRIORITY);

    if (!loaded) {
        try {
            // ... to do a bunch of loading.
            if (startUpImageURL != null) {
                tellLoadingMsg(startUpImageURL, imageLabel);
                startUpImage = getImage(startUpImageURL);
                tracker.addImage(startUpImage, STARTUP_ID);
                tracker.waitForID(STARTUP_ID);
                if (tracker.isErrorID(STARTUP_ID)) {
                    loadError(startUpImageURL, "start-up image");
                }
                Dimension size = getImageDimensions(startUpImage);
                resize(size.width, size.height);
                repaint();
            }

            if (backgroundImageURL != null) {
                tellLoadingMsg(backgroundImageURL, imageLabel);
                backgroundImage = getImage(backgroundImageURL);
                tracker.addImage(backgroundImage, BACKGROUND_ID);
                tracker.waitForID(BACKGROUND_ID);
                if (tracker.isErrorID(BACKGROUND_ID)) {
                    loadError(backgroundImageURL, "background image");
                }
                updateMaxDims(getImageDimensions(backgroundImage));
                repaint();
            }

            // Fetch the animation frames
            if (!fetchImages(images)) {
                // Need to add method to MediaTracker to return
                // files that caused errors during loading.
                loadError("an image", imageLabel);
                return;
            }

            if (soundtrackURL != null && soundtrack == null) {
                tellLoadingMsg(soundtrackURL, imageLabel);
                soundtrack = getAudioClip(soundtrackURL);
                if (soundtrack == null) {
                    loadError(soundtrackURL, "soundtrack");
                    return;
                }
            }

            if (sounds != null) {
                badURL = fetchSounds(sounds);
                if (badURL != null) {
                    loadError(badURL, soundLabel);
                    return;
                }
            }

            clearLoadingMessage();

            offScrImage = createImage(maxWidth, maxHeight);
            offScrGC = offScrImage.getGraphics();
            offScrGC.setColor(Color.white);

            resize(maxWidth, maxHeight);
            loaded = true;
            error = false;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
        }
    }

    if (userPause) {
        return;
    }

    if (repeat || frameNum < images.size()) {
        startPlaying();
    }

    try {
        if (images.size() > 1) {
            while (maxWidth > 0 && maxHeight > 0 && engine == me) {
                if (frameNum >= images.size()) {
                    if (!repeat) {
                        return;
                    }
                    setFrameNum(0);
                }
                repaint();

                if (sounds != null) {
                    AudioClip clip = (AudioClip) sounds.get(frameNumKey);
                    if (clip != null) {
                        clip.play();
                    }
                }

                try {
                    Integer pause = null;
                    if (durations != null) {
                        pause = (Integer) durations.get(frameNumKey);
                    }
                    if (pause == null) {
                        Thread.sleep(globalPause);
                    } else {
                        Thread.sleep(pause.intValue());
                    }
                } catch (InterruptedException e) {
                    // Should we do anything?
                }
                setFrameNum(frameNum + 1);
            }
        }
    } finally {
        stopPlaying();
    }
}

From source file:com.xabber.android.data.connection.ConnectionThread.java

public ConnectionThread(final ConnectionItem connectionItem) {
    LogManager.i(this, "NEW connection thread " + connectionItem.getRealJid());

    this.connectionItem = connectionItem;
    executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override/*  www.  jav a 2s. c  o m*/
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable,
                    "Connection thread for " + (connectionItem instanceof AccountItem
                            ? ((AccountItem) connectionItem).getAccount()
                            : connectionItem));
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.setDaemon(true);
            return thread;
        }
    });
    ConnectionManager.getInstance().onConnection(this);
    ConnectionSettings connectionSettings = connectionItem.getConnectionSettings();
    protocol = connectionSettings.getProtocol();
    serverName = connectionSettings.getServerName();
    token = connectionSettings.getPassword();
    resource = connectionSettings.getResource();
    saslEnabled = connectionSettings.isSaslEnabled();
    tlsMode = connectionSettings.getTlsMode();
    compression = connectionSettings.useCompression();
    if (saslEnabled && protocol == AccountProtocol.gtalk)
        login = connectionSettings.getUserName() + "@" + connectionSettings.getServerName();
    else
        login = connectionSettings.getUserName();
    proxyType = connectionSettings.getProxyType();
    proxyHost = connectionSettings.getProxyHost();
    proxyPort = connectionSettings.getProxyPort();
    proxyUser = connectionSettings.getProxyUser();
    proxyPassword = connectionSettings.getProxyPassword();
    started = false;
}

From source file:com.google.dart.compiler.metrics.Tracer.java

private BlockingQueue<TraceEvent> openLogWriter(final Writer writer, final String fileName) {
    try {/*from w  w w  .ja v  a 2  s. co  m*/
        if (outputFormat.equals(Format.HTML)) {
            writer.write("<HTML isdump=\"true\"><body>"
                    + "<style>body {font-family:Helvetica; margin-left:15px;}</style>"
                    + "<h2>Performance dump from GWT</h2>"
                    + "<div>This file contains data that can be viewed with the "
                    + "<a href=\"http://code.google.com/speedtracer\">SpeedTracer</a> "
                    + "extension under the <a href=\"http://chrome.google.com/\">"
                    + "Chrome</a> browser.</div><p><span id=\"info\">"
                    + "(You must install the SpeedTracer extension to open this file)</span></p>"
                    + "<div style=\"display: none\" id=\"traceData\" version=\"0.17\">\n");
        }
    } catch (IOException e) {
        System.err
                .println("Unable to write to dart.speedtracerlog '" + (fileName == null ? "" : fileName) + "'");
        e.printStackTrace();
        return null;
    }

    final BlockingQueue<TraceEvent> eventQueue = new LinkedBlockingQueue<TraceEvent>();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                // Wait for the other thread to drain the queue.
                eventQueue.add(shutDownSentinel);
                shutDownLatch.await();
            } catch (InterruptedException e) {
                // Ignored
            }
        }
    });

    // Background thread to write SpeedTracer events to log
    Thread logWriterWorker = new LogWriterThread(writer, fileName, eventQueue);

    // Lower than normal priority.
    logWriterWorker.setPriority((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2);

    /*
     * This thread must be daemon, otherwise shutdown hooks would never begin to
     * run, and an app wouldn't finish.
     */
    logWriterWorker.setDaemon(true);
    logWriterWorker.setName("SpeedTracerLogger writer");
    logWriterWorker.start();
    return eventQueue;
}

From source file:tvbrowser.extras.reminderplugin.ReminderPlugin.java

private void saveReminders() {
    Thread thread = new Thread("Save reminders") {
        @Override/*from  w w  w  . j  a v  a2 s.  c o  m*/
        public void run() {
            store();
        }
    };
    thread.setPriority(Thread.MIN_PRIORITY);
    thread.start();
}

From source file:org.n52.ifgicopter.spf.SPFRegistry.java

/**
 * Initialize all registered modules./*from   ww w . jav  a2 s.  c  o  m*/
 * 
 * @throws ClassNotFoundException
 *         if the class to be reflected is not in the classpath.
 * @throws InstantiationException
 *         if the class to be reflected could not be instantiated.
 * @throws IllegalAccessException
 *         if the class to be reflected is not accessible
 */
private void initModules() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException e) {
        log.warn(e.getMessage(), e);
    } catch (InstantiationException e) {
        log.warn(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        log.warn(e.getMessage(), e);
    } catch (UnsupportedLookAndFeelException e) {
        log.warn(e.getMessage(), e);
    }

    SplashDialog splash = new SplashDialog();
    Thread t = new Thread(splash);
    t.setPriority(Thread.MAX_PRIORITY);
    t.start();

    this.modules = new ArrayList<IModule>();
    this.engine = new SPFEngine();
    this.mainFrame = new SPFMainFrame();
    this.engine.setMainFrame(this.mainFrame);
    this.engine.addPositionListener(this.mainFrame.getMapPanel());
    this.statusChangeListeners = new ArrayList<IStatusChangeListener>();
    this.outputMessageListeners = new ArrayList<IOutputMessageListener>();

    /*
     * IOutputPlugins
     */
    List<IOutputPlugin> oplugs = new ArrayList<IOutputPlugin>();

    String tmp = this.properties.getProperty(OUTPUT_PLUGINS_PROP);
    if (tmp == null)
        log.warn("No config parameter " + OUTPUT_PLUGINS_PROP + " given.");
    else {

        tmp = tmp.trim();
        String[] oplugins = tmp.split(LIST_SEPARATOR);
        String[] params = null;
        Class<?>[] paramsClassArray = null;

        if (!tmp.equals("")) {

            // int opCount = 1;
            for (String classString : oplugins) {
                classString = classString.trim();

                if (classString.length() == 0)
                    continue;

                /*
                 * do we have any parameters?
                 */
                int pos = classString.indexOf("(");
                if (pos > 0) {
                    params = classString.substring(pos + 1, classString.length() - 1).split(",");
                    paramsClassArray = new Class[params.length];
                    if (params.length > 0) {
                        for (int i = 0; i < params.length; i++) {
                            paramsClassArray[i] = String.class;
                            params[i] = params[i].trim();
                        }
                        classString = classString.substring(0, pos);
                    }
                }

                Class<?> clazz;
                try {
                    clazz = Class.forName(classString);
                } catch (ClassNotFoundException e) {
                    log.error(null, e);
                    continue;
                } catch (NoClassDefFoundError e) {
                    log.error(null, e);
                    continue;
                }

                try {
                    IOutputPlugin oplugin = null;

                    if (params != null && params.length > 0) {
                        Constructor<?> constructor = clazz.getConstructor(paramsClassArray);
                        oplugin = (IOutputPlugin) constructor.newInstance((Object[]) params);
                        params = null;
                        paramsClassArray = null;
                    } else {
                        try {
                            oplugin = ((IOutputPlugin) clazz.newInstance());
                        } catch (InstantiationException e) {
                            log.error(null, e);
                            continue;
                        }
                    }

                    oplugs.add(oplugin);

                } catch (IllegalAccessException e) {
                    log.error("Could not access class with name '" + classString + "'.", e);
                } catch (InstantiationException e) {
                    log.error("Could not instantiate class with name '" + classString + "'.", e);
                } catch (SecurityException e) {
                    log.error(null, e);
                } catch (NoSuchMethodException e) {
                    log.error(
                            "A constructor with "
                                    + ((paramsClassArray == null) ? "NULL"
                                            : Integer.valueOf(paramsClassArray.length))
                                    + " String arguments for Class " + clazz.getName() + " could not be found.",
                            e);
                } catch (IllegalArgumentException e) {
                    log.error(null, e);
                } catch (InvocationTargetException e) {
                    log.error(null, e);
                } catch (ClassCastException e) {
                    log.error(clazz.getName() + " is not an instance of IOutputPlugin! Could not instantiate.",
                            e);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

                // opCount++;
            }
        } else
            log.warn(OUTPUT_PLUGINS_PROP + " is empty, no output plugins defined.");
    }

    /*
     * worker threadpool
     */
    this.threadPool = SPFThreadPool.getInstance();
    this.modules.add(this.threadPool);

    /*
     * IInputPlugins
     */
    List<IInputPlugin> iplugs = new ArrayList<IInputPlugin>();

    tmp = this.properties.getProperty(INPUT_PLUGINS_PROP);
    if (tmp == null) {
        log.warn("No config parameter " + INPUT_PLUGINS_PROP + " given.");
    } else {
        tmp = tmp.trim();
        String[] params = null;
        Class<?>[] paramsClassArray = null;
        String[] iplugins = tmp.split(LIST_SEPARATOR);

        if (!tmp.equals("")) {
            for (String classString : iplugins) {
                classString = classString.trim();

                if (classString.length() == 0)
                    continue;

                /*
                 * do we have any parameters?
                 */
                int pos = classString.indexOf("(");
                if (pos > 0) {
                    params = classString.substring(pos + 1, classString.length() - 1).split(",");
                    paramsClassArray = new Class[params.length];
                    if (params.length > 0) {
                        for (int i = 0; i < params.length; i++) {
                            paramsClassArray[i] = String.class;
                            params[i] = params[i].trim();
                        }
                        classString = classString.substring(0, pos);
                    }
                }

                Class<?> clazz;
                try {
                    clazz = Class.forName(classString);
                } catch (ClassNotFoundException e) {
                    log.error(null, e);
                    continue;
                } catch (NoClassDefFoundError e) {
                    log.error(null, e);
                    continue;
                }

                if (clazz != null) {
                    IInputPlugin iplugin = null;
                    if (pos > 0) {
                        try {
                            Constructor<?> constructor = clazz.getConstructor(paramsClassArray);
                            iplugin = (IInputPlugin) constructor.newInstance((Object[]) params);
                        } catch (IllegalAccessException e) {
                            log.error("Could not access class with name '" + classString + "'.", e);
                        } catch (InstantiationException e) {
                            log.error("Could not instantiate class with name '" + classString + "'.", e);
                        } catch (SecurityException e) {
                            log.error(null, e);
                        } catch (NoSuchMethodException e) {
                            log.error("A constructor with "
                                    + ((paramsClassArray == null) ? "NULL"
                                            : Integer.valueOf(paramsClassArray.length))
                                    + " String arguments for Class " + clazz.getName() + " could not be found.",
                                    e);
                        } catch (IllegalArgumentException e) {
                            log.error(null, e);
                        } catch (InvocationTargetException e) {
                            log.error(null, e);
                        } catch (ClassCastException e) {
                            log.error(clazz.getName()
                                    + " is not an instance of IInputPlugin! Could not instantiate.", e);
                        }

                        params = null;
                        paramsClassArray = null;
                    } else {
                        try {
                            iplugin = (IInputPlugin) clazz.newInstance();
                        } catch (InstantiationException e) {
                            log.error(null, e);
                            continue;
                        }
                    }
                    iplugs.add(iplugin);
                }
            }
        } else
            log.warn(INPUT_PLUGINS_PROP + " is empty, no input plugins defined.");
    }

    /*
     * AbstractDataProcessors
     */
    tmp = this.properties.getProperty(ABSTRACT_DATA_PROCESSORS).trim();
    String[] dps = tmp.split(LIST_SEPARATOR);

    this.dataProcessors = new ArrayList<Class<?>>();
    if (!tmp.equals("")) {
        for (String classString : dps) {
            String[] params = null;
            Class<?>[] paramsClassArray = null;
            classString = classString.trim();

            /*
             * do we have any parameters?
             */
            int pos = classString.indexOf("(");
            if (pos > 0) {
                params = classString.substring(pos + 1, classString.length() - 1).split(",");
                paramsClassArray = new Class[params.length];
                if (params.length > 0) {
                    for (int i = 0; i < params.length; i++) {
                        paramsClassArray[i] = String.class;
                        params[i] = params[i].trim();
                    }
                    classString = classString.substring(0, pos);
                }
            }

            Class<?> clazz;
            try {
                clazz = Class.forName(classString);
            } catch (ClassNotFoundException e) {
                log.error(null, e);
                continue;
            } catch (NoClassDefFoundError e) {
                log.error(null, e);
                continue;
            }

            this.dataProcessors.add(clazz);
        }
    }

    loadExtensions();

    splash.activateProgressBar(
            this.modules.size() + this.dataProcessors.size() + iplugs.size() + oplugs.size());

    /*
     * initialise all modules
     */
    for (IModule module : this.modules) {
        if (module != null) {
            try {
                module.init();
            } catch (Exception e) {
                log.warn(null, e);
            }
        }
        splash.processFinished();
    }

    /*
     * as a last step startup of all output and input plugins as they should not create data before other
     * parts are running.
     */
    for (IOutputPlugin iOutputPlugin : oplugs) {
        if (iOutputPlugin == null)
            continue;
        try {
            registerOutputPlugin(iOutputPlugin);
        } catch (Throwable e) {
            log.warn(e.getMessage(), e);
        }
        splash.processFinished();
    }

    for (IInputPlugin iInputPlugin : iplugs) {
        if (iInputPlugin == null)
            continue;
        try {
            registerInputPlugin(iInputPlugin);
        } catch (Throwable e) {
            log.warn(e.getMessage(), e);
        }
        splash.processFinished();
    }

    /*
     * add all status change listeners
     */
    this.statusChangeListeners.add(this.mainFrame);
    this.outputMessageListeners.add(this.mainFrame);

    /*
     * set the default view
     */
    this.mainFrame.switchToDefaultTab();

    splash.removeSelf();

    this.mainFrame.setVisible(true);
    this.engine.start();

    lifecycleLog.info("Module loading completed.");
}

From source file:com.amazon.mws.shared.MwsConnection.java

/**
 * Get the shared executor service that is used by async calls if no
 * executor is supplied.//from ww  w  . java 2 s.c  o m
 * 
 * @return The shared executor service.
 */
private ExecutorService getSharedES() {
    synchronized (this.getClass()) {
        if (sharedES != null) {
            return sharedES;
        }
        sharedES = new ThreadPoolExecutor(maxAsyncThreads / 10, maxAsyncThreads, 60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(maxAsyncQueueSize), new ThreadFactory() {
                    private final AtomicInteger threadNumber = new AtomicInteger(1);

                    public Thread newThread(Runnable task) {
                        Thread thread = new Thread(task, "MWSClient-" + threadNumber.getAndIncrement());
                        thread.setDaemon(true);
                        thread.setPriority(Thread.NORM_PRIORITY);
                        return thread;
                    }
                }, new RejectedExecutionHandler() {
                    public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
                        if (!executor.isShutdown()) {
                            log.warn("MWSClient async queue full, running on calling thread.");
                            task.run();
                        } else {
                            throw new RejectedExecutionException();
                        }
                    }
                });
        return sharedES;
    }
}

From source file:gda.device.detector.analyser.EpicsMCASimple.java

RegisterForEpicsUpdates(IEpicsDevice epicsDevice, List<EpicsRegistrationRequest> requests, IObserver observer) {
    this.epicsDevice = epicsDevice;
    this.requests = requests;
    this.observer = observer;
    Thread t = uk.ac.gda.util.ThreadManager.getThread(this);
    t.setPriority(java.lang.Thread.MIN_PRIORITY);
    t.start();//from   w ww.  ja  va  2s.co  m
}