Example usage for java.lang Thread NORM_PRIORITY

List of usage examples for java.lang Thread NORM_PRIORITY

Introduction

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

Prototype

int NORM_PRIORITY

To view the source code for java.lang Thread NORM_PRIORITY.

Click Source Link

Document

The default priority that is assigned to a thread.

Usage

From source file:com.amazonservices.mws.client.MwsConnection.java

/**
 * Get the shared executor service that is used by async calls if no
 * executor is supplied.// w w w  .j ava 2  s.  c  om
 * 
 * @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);

                    //@Override
                    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() {
                    //@Override
                    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:net.spfbl.dns.QueryDNS.java

/**
 * Configurao e intanciamento do servidor.
 * @throws java.net.SocketException se houver falha durante o bind.
 *///from   www.j  a v  a2 s.  c  o m
public QueryDNS(int port) throws SocketException {
    super("SERVERDNS");
    setPriority(Thread.NORM_PRIORITY);
    // Criando conexes.
    Server.logDebug("binding DNS socket on port " + port + "...");
    PORT = port;
    SERVER_SOCKET = new DatagramSocket(port);
    Server.logTrace(getName() + " thread allocation.");
}

From source file:org.archive.crawler.frontier.AbstractFrontier.java

/**
 * Start the dedicated() thread with an independent view of the frontier's
 * state. /* w w  w . jav  a 2s.  co  m*/
 * 
 * <p>??
 */
protected void startManagerThread() {
    managerThread = new Thread(this + ".managerThread") {
        public void run() {
            AbstractFrontier.this.managementTasks();
        }
    };
    managerThread.setPriority(Thread.NORM_PRIORITY + 1);
    managerThread.start();
}

From source file:net.spfbl.http.ServerHTTP.java

/**
 * Configurao e intanciamento do servidor.
 * @param port a porta HTTPS a ser vinculada.
 * @throws java.io.IOException se houver falha durante o bind.
 *///from  www.  ja  v  a2 s  .c om
public ServerHTTP(String hostname, int port) throws IOException {
    super("SERVERHTP");
    HOSTNAME = hostname;
    PORT = port;
    setPriority(Thread.NORM_PRIORITY);
    // Criando conexes.
    Server.logDebug("binding HTTP socket on port " + port + "...");
    SERVER = HttpServer.create(new InetSocketAddress(port), 0);
    SERVER.createContext("/", new AccessHandler());
    SERVER.setExecutor(null); // creates a default executor
    Server.logTrace(getName() + " thread allocation.");
}

From source file:net.dv8tion.jda.audio.AudioConnection.java

private void setupSendThread() {
    if (sendThread == null && udpSocket != null && sendHandler != null) {
        sendThread = new Thread("AudioConnection SendThread Guild: " + channel.getGuild().getId()) {
            @Override/*from   w w w .j  a  v  a 2s  . c o  m*/
            public void run() {
                char seq = 0; //Sequence of audio packets. Used to determine the order of the packets.
                int timestamp = 0; //Used to sync up our packets within the same timeframe of other people talking.
                long lastFrameSent = System.currentTimeMillis();
                boolean sentSilenceOnConnect = false;
                while (!udpSocket.isClosed() && !this.isInterrupted()) {
                    try {
                        //WE NEED TO CONSIDER BUFFERING STUFF BECAUSE REASONS.
                        //Consider storing 40-60ms of encoded audio as a buffer.
                        if (sentSilenceOnConnect && sendHandler != null && sendHandler.canProvide()) {
                            silenceCounter = -1;
                            byte[] rawAudio = sendHandler.provide20MsAudio();
                            if (rawAudio == null || rawAudio.length == 0) {
                                if (speaking && (System.currentTimeMillis()
                                        - lastFrameSent) > OPUS_FRAME_TIME_AMOUNT)
                                    setSpeaking(false);
                            } else {
                                if (!sendHandler.isOpus()) {
                                    rawAudio = encodeToOpus(rawAudio);
                                }
                                AudioPacket packet = new AudioPacket(seq, timestamp, webSocket.getSSRC(),
                                        rawAudio);
                                if (!speaking)
                                    setSpeaking(true);
                                udpSocket.send(packet.asEncryptedUdpPacket(webSocket.getAddress(),
                                        webSocket.getSecretKey()));

                                if (seq + 1 > Character.MAX_VALUE)
                                    seq = 0;
                                else
                                    seq++;
                            }
                        } else if (silenceCounter > -1) {
                            AudioPacket packet = new AudioPacket(seq, timestamp, webSocket.getSSRC(),
                                    silenceBytes);
                            udpSocket.send(packet.asEncryptedUdpPacket(webSocket.getAddress(),
                                    webSocket.getSecretKey()));

                            if (seq + 1 > Character.MAX_VALUE)
                                seq = 0;
                            else
                                seq++;

                            if (++silenceCounter > 10) {
                                silenceCounter = -1;
                                sentSilenceOnConnect = true;
                            }
                        } else if (speaking
                                && (System.currentTimeMillis() - lastFrameSent) > OPUS_FRAME_TIME_AMOUNT)
                            setSpeaking(false);
                    } catch (NoRouteToHostException e) {
                        LOG.warn("Closing AudioConnection due to inability to send audio packets.");
                        LOG.warn("Cannot send audio packet because JDA cannot navigate the route to Discord.\n"
                                + "Are you sure you have internet connection? It is likely that you've lost connection.");
                        webSocket.close(true, -1);
                    } catch (SocketException e) {
                        //Most likely the socket has been closed due to the audio connection be closed. Next iteration will kill loop.
                    } catch (Exception e) {
                        LOG.log(e);
                    } finally {
                        timestamp += OPUS_FRAME_SIZE;
                        long sleepTime = (OPUS_FRAME_TIME_AMOUNT)
                                - (System.currentTimeMillis() - lastFrameSent);
                        if (sleepTime > 0) {
                            try {
                                Thread.sleep(sleepTime);
                            } catch (InterruptedException e) {
                                //We've been asked to stop. The next iteration will kill the loop. 
                            }
                        }
                        if (System.currentTimeMillis() < lastFrameSent + 60) // If the sending didn't took longer than 60ms (3 times the time frame)
                        {
                            lastFrameSent += OPUS_FRAME_TIME_AMOUNT; // incrase lastFrameSent
                        } else {
                            lastFrameSent = System.currentTimeMillis(); // else reset lastFrameSent to current time
                        }
                    }
                }
            }
        };
        sendThread.setPriority((Thread.NORM_PRIORITY + Thread.MAX_PRIORITY) / 2);
        sendThread.setDaemon(true);
        sendThread.start();
    }
}

From source file:de.juwimm.cms.content.modules.ModuleFactoryStandardImpl.java

public void reconfigureModules(Hashtable<String, Element> htModuleDcfNameDcfElement) {
    Collection coll = this.htModules.values();
    Iterator it = coll.iterator();
    while (it.hasNext()) {
        Module module = (Module) it.next();
        Thread t = new Thread(Thread.currentThread().getThreadGroup(),
                new ReconfigureModuleRunnable(module, htModuleDcfNameDcfElement, htInitialContent));
        t.setPriority(Thread.NORM_PRIORITY);
        t.setName("ReconfigureModuleRunnable");
        t.start();//from   w w w .ja  v a2 s .  c  o m
    }
}

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();
    }//from w w w  .  j av a2s.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:com.grass.caishi.cc.MyApplication.java

/** ?ImageLoader */
public static void initImageLoader(Context context) {
    File cacheDir = StorageUtils.getOwnCacheDirectory(context, Constant.CACHE_LOAND_IMAGE);// ??
    // Log.d("cacheDir"+ cacheDir.getPath() );
    // ?ImageLoader(?,?)?APPLACATION???
    // ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
    // // ?/* w ww. j a va  2s.  com*/
    // .threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2).memoryCache(new WeakMemoryCache()).denyCacheImageMultipleSizesInMemory()
    // /***
    // * *** / .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) .memoryCacheSize(2 * 1024 * 1024) .memoryCacheSizePercentage(13) // default /***end
    // ***/
    // .discCacheFileNameGenerator(new Md5FileNameGenerator())
    // // ?URI??MD5 
    // .tasksProcessingOrder(QueueProcessingType.LIFO).discCache(new UnlimitedDiscCache(cacheDir))// 
    // // .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
    // .writeDebugLogs() // Remove for release app
    // .build();
    // // Initialize ImageLoader with configuration.
    // ImageLoader.getInstance().init(config);// ??

    ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
    config.threadPriority(Thread.NORM_PRIORITY - 2);
    config.denyCacheImageMultipleSizesInMemory();
    config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
    config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
    config.tasksProcessingOrder(QueueProcessingType.LIFO);
    // config.diskCache(DefaultConfigurationFactory.createDiskCache(applicationContext, cacheDir, 0, 0));
    // config.writeDebugLogs(); // Remove for release app

    // Initialize ImageLoader with configuration.
    ImageLoader.getInstance().init(config.build());
}

From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java

/**
 * Constructs MarketplaceWebServiceClient with AWS Access Key ID, AWS Secret Key
 * and MarketplaceWebServiceConfig. Use MarketplaceWebServiceConfig to pass additional
 * configuration that affects how service is being called.
 *
 * @param awsAccessKeyId/*from w  ww . j  a  v  a  2s.c om*/
 *          AWS Access Key ID
 * @param awsSecretAccessKey
 *          AWS Secret Access Key
 * @param config
 *          Additional configuration options
 */
@SuppressWarnings("serial")
public MarketplaceWebServiceClient(String awsAccessKeyId, String awsSecretAccessKey, String applicationName,
        String applicationVersion, MarketplaceWebServiceConfig config) {
    this.awsAccessKeyId = awsAccessKeyId;
    this.awsSecretAccessKey = awsSecretAccessKey;
    this.config = config;
    this.httpClient = configureHttpClient(applicationName, applicationVersion);
    this.asyncExecutor = new ThreadPoolExecutor(config.getMaxAsyncThreads(), config.getMaxAsyncThreads(), 60L,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(config.getMaxAsyncQueueSize()) {

                @Override
                public boolean offer(Runnable task) {
                    log.debug("Maximum number of concurrent threads reached, queuing task...");
                    return super.offer(task);
                }
            }, new ThreadFactory() {

                private final AtomicInteger threadNumber = new AtomicInteger(1);

                public Thread newThread(Runnable task) {
                    Thread thread = new Thread(task,
                            "MarketplaceWebServiceClient-Thread-" + threadNumber.getAndIncrement());
                    thread.setDaemon(true);
                    if (thread.getPriority() != Thread.NORM_PRIORITY) {
                        thread.setPriority(Thread.NORM_PRIORITY);
                    }
                    log.debug("ThreadFactory created new thread: " + thread.getName());
                    return thread;
                }
            }, new RejectedExecutionHandler() {

                public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
                    log.debug("Maximum number of concurrent threads reached, and queue is full. "
                            + "Running task in the calling thread..." + Thread.currentThread().getName());
                    if (!executor.isShutdown()) {
                        task.run();
                    }
                }
            });
}