Example usage for java.util.concurrent.locks ReentrantLock ReentrantLock

List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReentrantLock ReentrantLock.

Prototype

public ReentrantLock() 

Source Link

Document

Creates an instance of ReentrantLock .

Usage

From source file:org.omnaest.utils.structure.map.MapUtils.java

/**
 * Returns a view of the given {@link Map} using a new {@link ReentrantLock} instance to synchronize all of its methods
 * //from  w  w  w . j a v a  2  s .co  m
 * @see #locked(Map, Lock)
 * @param map
 * @return
 */
public static <K, V> Map<K, V> lockedByReentrantLock(Map<K, V> map) {
    Lock lock = new ReentrantLock();
    return locked(map, lock);
}

From source file:org.apache.openjpa.kernel.BrokerImpl.java

public void setMultithreaded(boolean multithreaded) {
    assertOpen();/*from   w w  w .j a v  a2  s.c o m*/
    _multithreaded = multithreaded;
    if (multithreaded && _lock == null)
        _lock = new ReentrantLock();
    else if (!multithreaded)
        _lock = null;
}

From source file:SwingWorker.java

/**
 * returns workersExecutorService./*from   w  w  w .java  2s  . c  o m*/
 *
 * returns the service stored in the appContext or creates it if
 * necessary. If the last one it triggers autoShutdown thread to
 * get started.
 * 
 * @return ExecutorService for the {@code SwingWorkers}
 * @see #startAutoShutdownThread
 */
private static synchronized ExecutorService getWorkersExecutorService() {
    if (executorService == null) {
        //this creates non-daemon threads. 
        ThreadFactory threadFactory = new ThreadFactory() {
            final ThreadFactory defaultFactory = Executors.defaultThreadFactory();

            public Thread newThread(final Runnable r) {
                Thread thread = defaultFactory.newThread(r);
                thread.setName("SwingWorker-" + thread.getName());
                return thread;
            }
        };

        /*
         * We want a to have no more than MAX_WORKER_THREADS
         * running threads.
         *
         * We want a worker thread to wait no longer than 1 second
         * for new tasks before terminating.
         */
        executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS, 1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), threadFactory) {

            private final ReentrantLock pauseLock = new ReentrantLock();
            private final Condition unpaused = pauseLock.newCondition();
            private boolean isPaused = false;
            private final ReentrantLock executeLock = new ReentrantLock();

            @Override
            public void execute(Runnable command) {
                /*
                 * ThreadPoolExecutor first tries to run task
                 * in a corePool. If all threads are busy it
                 * tries to add task to the waiting queue. If it
                 * fails it run task in maximumPool.
                 *
                 * We want corePool to be 0 and
                 * maximumPool to be MAX_WORKER_THREADS
                 * We need to change the order of the execution.
                 * First try corePool then try maximumPool
                 * pool and only then store to the waiting
                 * queue. We can not do that because we would
                 * need access to the private methods.
                 *
                 * Instead we enlarge corePool to
                 * MAX_WORKER_THREADS before the execution and
                 * shrink it back to 0 after. 
                 * It does pretty much what we need.
                 *
                 * While we changing the corePoolSize we need
                 * to stop running worker threads from accepting new
                 * tasks.
                 */

                //we need atomicity for the execute method.
                executeLock.lock();
                try {

                    pauseLock.lock();
                    try {
                        isPaused = true;
                    } finally {
                        pauseLock.unlock();
                    }

                    setCorePoolSize(MAX_WORKER_THREADS);
                    super.execute(command);
                    setCorePoolSize(0);

                    pauseLock.lock();
                    try {
                        isPaused = false;
                        unpaused.signalAll();
                    } finally {
                        pauseLock.unlock();
                    }
                } finally {
                    executeLock.unlock();
                }
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                pauseLock.lock();
                try {
                    while (isPaused) {
                        unpaused.await();
                    }
                } catch (InterruptedException ignore) {

                } finally {
                    pauseLock.unlock();
                }
            }
        };
    }
    return executorService;
}

From source file:de.dkfz.roddy.client.fxuiclient.RoddyUIController.java

/**
 * Check and (re-)open / get an (active) rmi server + connection
 *
 * @return//from  w  ww .  j av  a  2s. c o  m
 */
public RoddyRMIClientConnection getRMIConnection(String analysis) {
    if (RoddyConversionHelperMethods.isNullOrEmpty(analysis) && !analysis.contains("::"))
        System.err.println(
                "Malformed analysis " + analysis + " for getRMIConnection(), needs to be fully specified.");
    List<String> dissected = ProjectFactory.dissectFullAnalysisID(analysis);
    String pluginID = dissected.get(0);

    String shortAnalysisId = analysis.split("[:][:]")[0];
    ReentrantLock myLock = null;
    synchronized (rmiLocks) {
        if (!rmiLocks.containsKey(pluginID)) {
            rmiLocks.put(pluginID, new ReentrantLock());
        }
        myLock = rmiLocks.get(pluginID);
    }

    RoddyRMIClientConnection connection = null;
    logger.postAlwaysInfo("Locking for " + analysis);
    myLock.lock();
    try {
        if (!rmiConnectionPool.containsKey(pluginID) || !rmiConnectionPool.get(pluginID).pingServer()) {
            logger.postAlwaysInfo("Creating connection for " + analysis);
            RoddyRMIClientConnection clientConnection = new RoddyRMIClientConnection();
            clientConnection.startLocalRoddyRMIServerAndConnect(currentIniFile.getAbsolutePath(),
                    currentProjectWrapper.getName(), shortAnalysisId);
            rmiConnectionPool.put(pluginID, clientConnection);
        }
        logger.postAlwaysInfo("Retrieving connection for " + analysis);
        connection = rmiConnectionPool.get(pluginID);
    } finally {
        myLock.unlock();
    }
    return connection;
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Schedules a new task/*from ww  w  . j a  v  a 2 s. c  om*/
 *
 * @param task the <code>ScheduledTaskWrapper</code> to schedule
 * @param delay the delay in the scheduling (it must be greater than 1 second
 *        otherwise the delay is set automatically to 1 sec)
 */
protected void scheduleTask(ScheduledTaskWrapper task, long delay) {
    if (task == null) {
        if (log.isTraceEnabled()) {
            log.trace("Trying to schedule a null task. Request rejected");
        }
        return;
    }
    //
    // We don't get any task lock, but the caller should do (see updateTask or
    // removeTask or scheduleTask(ScheduledTaskWrapper))
    //

    //
    // This is used below...see there for a description
    //
    Lock taskExecutionLock = null;
    try {

        if (!ScheduledTaskWrapper.State.CONFIGURED.equals(task.getState())
                && !ScheduledTaskWrapper.State.SCHEDULED.equals(task.getState())) {
            //
            // We log the error creating an empty exception in order to have
            // the stacktrace
            //
            log.error("Trying to schedule a not configured or scheduled task. Request rejected",
                    new Exception());

            return;
        }
        long period = task.getPeriod();
        TimeUnit timeUnit = TimeUnit.MILLISECONDS;
        if (period == 0) {
            period = 1;
            timeUnit = TimeUnit.NANOSECONDS;
        }

        if (log.isTraceEnabled()) {
            log.trace("Scheduling task: " + task);
        }
        //
        // We use the execution lock to avoid the task execution before putting
        // it in the scheduledFutures map.
        // See ScheduledTaskWrapper.execute
        //
        taskExecutionLock = new ReentrantLock();
        taskExecutionLock.lock();
        task.setExecutionLock(taskExecutionLock);
        ScheduledFuture scheduledFuture = scheduleWithFixedDelay(task, delay, period, timeUnit);

        task.setState(ScheduledTaskWrapper.State.SCHEDULED);

        //
        // Since DualHashBidiMap is not synchronized we need to sync the write
        // access
        //
        synchronized (scheduledFutures) {
            scheduledFutures.put(task, scheduledFuture);
        }
    } finally {
        taskExecutionLock.unlock();
    }
}

From source file:org.wso2.carbon.application.deployer.synapse.SynapseAppDeployer.java

/**
 * Acquires the lock/*ww w .j  ava  2s  .c o m*/
 *
 * @param axisConfig AxisConfiguration instance
 * @return Lock instance
 */
protected Lock getLock(AxisConfiguration axisConfig) {
    Parameter p = axisConfig.getParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK);
    if (p != null) {
        return (Lock) p.getValue();
    } else {
        log.warn(ServiceBusConstants.SYNAPSE_CONFIG_LOCK + " is null, Recreating a new lock");
        Lock lock = new ReentrantLock();
        try {
            axisConfig.addParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK, lock);
            return lock;
        } catch (AxisFault axisFault) {
            log.error("Error while setting " + ServiceBusConstants.SYNAPSE_CONFIG_LOCK);
        }
    }

    return null;
}

From source file:it.unimi.dsi.webgraph.algo.HyperBall.java

/** Creates a new HyperBall instance.
 * //from w  w w . j  ava 2  s.  c o  m
 * @param g the graph whose neighbourhood function you want to compute.
 * @param gt the transpose of <code>g</code>, or <code>null</code>.
 * @param log2m the logarithm of the number of registers per counter.
 * @param pl a progress logger, or <code>null</code>.
 * @param numberOfThreads the number of threads to be used (0 for automatic sizing).
 * @param bufferSize the size of an I/O buffer in bytes (0 for {@link #DEFAULT_BUFFER_SIZE}).
 * @param granularity the number of node per task in a multicore environment (it will be rounded to the next multiple of 64), or 0 for {@link #DEFAULT_GRANULARITY}.
 * @param external if true, results of an iteration will be stored on disk.
 * @param doSumOfDistances whether the sum of distances from each node should be computed.
 * @param doSumOfInverseDistances whether the sum of inverse distances from each node should be computed.
 * @param discountFunction an array (possibly <code>null</code>) of discount functions. 
 * @param seed the random seed passed to {@link HyperLogLogCounterArray#HyperLogLogCounterArray(long, long, int, long)}.
 */
public HyperBall(final ImmutableGraph g, final ImmutableGraph gt, final int log2m, final ProgressLogger pl,
        final int numberOfThreads, final int bufferSize, final int granularity, final boolean external,
        final boolean doSumOfDistances, final boolean doSumOfInverseDistances,
        final Int2DoubleFunction[] discountFunction, final long seed) throws IOException {
    super(g.numNodes(), g.numNodes(), ensureRegisters(log2m), seed);

    info("Seed : " + Long.toHexString(seed));

    gotTranspose = gt != null;
    localNextMustBeChecked = gotTranspose
            ? IntSets.synchronize(new IntOpenHashSet(Hash.DEFAULT_INITIAL_SIZE, Hash.VERY_FAST_LOAD_FACTOR))
            : null;

    numNodes = g.numNodes();
    try {
        numArcs = g.numArcs();
    } catch (UnsupportedOperationException e) {
        // No number of arcs. We have to enumerate.
        long a = 0;
        final NodeIterator nodeIterator = g.nodeIterator();
        for (int i = g.numNodes(); i-- != 0;) {
            nodeIterator.nextInt();
            a += nodeIterator.outdegree();
        }
        numArcs = a;
    }
    squareNumNodes = (double) numNodes * numNodes;

    cumulativeOutdegrees = new EliasFanoCumulativeOutdegreeList(g, numArcs, Math.max(0, 64 / m - 1));

    modifiedCounter = new boolean[numNodes];
    modifiedResultCounter = external ? null : new boolean[numNodes];
    if (gt != null) {
        mustBeChecked = new boolean[numNodes];
        nextMustBeChecked = new boolean[numNodes];
        if (gt.numNodes() != g.numNodes())
            throw new IllegalArgumentException("The graph and its transpose have a different number of nodes");
        if (gt.numArcs() != g.numArcs())
            throw new IllegalArgumentException("The graph and its transpose have a different number of arcs");
    }

    this.pl = pl;
    this.external = external;
    this.doSumOfDistances = doSumOfDistances;
    this.doSumOfInverseDistances = doSumOfInverseDistances;
    this.discountFunction = discountFunction == null ? new Int2DoubleFunction[0] : discountFunction;
    this.numberOfThreads = numberOfThreads(numberOfThreads);
    this.granularity = numberOfThreads == 1 ? numNodes
            : granularity == 0 ? DEFAULT_GRANULARITY : ((granularity + Long.SIZE - 1) & ~(Long.SIZE - 1));
    this.bufferSize = Math.max(1, (bufferSize == 0 ? DEFAULT_BUFFER_SIZE : bufferSize)
            / ((Long.SIZE / Byte.SIZE) * (counterLongwords + 1)));

    info("Relative standard deviation: "
            + Util.format(100 * HyperLogLogCounterArray.relativeStandardDeviation(log2m)) + "% (" + m
            + " registers/counter, " + registerSize + " bits/register, " + Util.format(m * registerSize / 8.)
            + " bytes/counter)");
    if (external)
        info("Running " + this.numberOfThreads + " threads with a buffer of " + Util.formatSize(this.bufferSize)
                + " counters");
    else
        info("Running " + this.numberOfThreads + " threads");

    thread = new IterationThread[this.numberOfThreads];

    if (external) {
        info("Creating update list...");
        updateFile = File.createTempFile(HyperBall.class.getName(), "-temp");
        updateFile.deleteOnExit();
        fileChannel = (randomAccessFile = new RandomAccessFile(updateFile, "rw")).getChannel();
    } else {
        updateFile = null;
        fileChannel = null;
    }

    nodes = new AtomicInteger();
    arcs = new AtomicLong();
    modified = new AtomicInteger();
    unwritten = new AtomicInteger();

    neighbourhoodFunction = new DoubleArrayList();
    sumOfDistances = doSumOfDistances ? new float[numNodes] : null;
    sumOfInverseDistances = doSumOfInverseDistances ? new float[numNodes] : null;
    discountedCentrality = new float[this.discountFunction.length][];
    for (int i = 0; i < this.discountFunction.length; i++)
        discountedCentrality[i] = new float[numNodes];

    info("HyperBall memory usage: " + Util.formatSize2(usedMemory()) + " [not counting graph(s)]");

    if (!external) {
        info("Allocating result bit vectors...");
        // Allocate vectors that will store the result.
        resultBits = new long[bits.length][];
        resultRegisters = new LongBigList[bits.length];
        for (int i = bits.length; i-- != 0;)
            resultRegisters[i] = (LongArrayBitVector.wrap(resultBits[i] = new long[bits[i].length]))
                    .asLongBigList(registerSize);
    } else {
        resultBits = null;
        resultRegisters = null;
    }

    lock = new ReentrantLock();
    allWaiting = lock.newCondition();
    start = lock.newCondition();
    aliveThreads = this.numberOfThreads;

    if (this.numberOfThreads == 1)
        (thread[0] = new IterationThread(g, gt, 0)).start();
    else
        for (int i = 0; i < this.numberOfThreads; i++)
            (thread[i] = new IterationThread(g.copy(), gt != null ? gt.copy() : null, i)).start();

    // We wait for all threads being read to start.
    lock.lock();
    try {
        if (aliveThreads != 0)
            allWaiting.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        lock.unlock();
    }
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Returns the lock associated to the given object. Any thread that
 * must handle a task must, first of all, lock the handling task lock.
 * Locking a ScheduledTaskWrapper the key must be its id.
 * Locking a TaskWrapper the key is the task itself (it doesn't have an id).
 *
 * Note that maybe also for the ScheduledTaskWrapper we could use the task
 * itself but at the moment this change requires a lot of regression test.
 * The next one that reads this comment should try to review it in order to use
 * always the task as key.//  w  w  w  . j  a  v  a  2  s .  co  m
 *
 * @param key the key of the lock (could be the task itself or its id)
 * @return the lock associated to the key
 */
private Lock getHandlingTaskLock(Object key) {

    if (key != null) {
        if (key instanceof ScheduledTaskWrapper) {
            key = ((ScheduledTaskWrapper) key).getId();
        }
    }

    Lock taskLock = null;
    readLock.lock();
    try {
        taskLock = taskLocks.get(key);
    } finally {
        readLock.unlock();
    }
    if (taskLock == null) {
        writeLock.lock();
        try {
            taskLock = taskLocks.get(key);
            if (taskLock == null) {
                taskLock = new ReentrantLock();
                taskLocks.put(key, taskLock);
            }
        } finally {
            writeLock.unlock();
        }
    }
    return taskLock;
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

/**
 * returns workersExecutorService.//from   w w w  . j a v a  2s .  c  om
 *
 * returns the service stored in the appContext or creates it if
 * necessary. If the last one it triggers autoShutdown thread to
 * get started.
 * 
 * @return ExecutorService for the {@code SwingWorkers}
 * @see #startAutoShutdownThread
 */
private static synchronized ExecutorService getWorkersExecutorService() {
    if (executorService == null) {
        //this creates non-daemon threads. 
        ThreadFactory threadFactory = 
            new ThreadFactory() {
                final AtomicInteger threadNumber = new AtomicInteger(1);
                public Thread newThread(final Runnable r) {
                    StringBuilder name = 
                        new StringBuilder("SwingWorker-pool-");
                    name.append(System.identityHashCode(this));
                    name.append("-thread-");
                    name.append(threadNumber.getAndIncrement());
                             
                    Thread t = new Thread(r, name.toString());;
                    if (t.isDaemon())
                        t.setDaemon(false);
                    if (t.getPriority() != Thread.NORM_PRIORITY)
                        t.setPriority(Thread.NORM_PRIORITY);
                    return t;
                }
            };

        /*
         * We want a to have no more than MAX_WORKER_THREADS
         * running threads.
         *
         * We want a worker thread to wait no longer than 1 second
         * for new tasks before terminating.
         */
        executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS,
                                     5L, TimeUnit.SECONDS,
                                     new LinkedBlockingQueue<Runnable>(),
                                     threadFactory) {

                private final ReentrantLock pauseLock = new ReentrantLock();
                private final Condition unpaused = pauseLock.newCondition();
                private boolean isPaused = false;
                private final ReentrantLock executeLock = new ReentrantLock();
                    
                @Override
                public void execute(Runnable command) {
                    /*
                     * ThreadPoolExecutor first tries to run task
                     * in a corePool. If all threads are busy it
                     * tries to add task to the waiting queue. If it
                     * fails it run task in maximumPool.
                     *
                     * We want corePool to be 0 and
                     * maximumPool to be MAX_WORKER_THREADS
                     * We need to change the order of the execution.
                     * First try corePool then try maximumPool
                     * pool and only then store to the waiting
                     * queue. We can not do that because we would
                     * need access to the private methods.
                     *
                     * Instead we enlarge corePool to
                     * MAX_WORKER_THREADS before the execution and
                     * shrink it back to 0 after. 
                     * It does pretty much what we need.
                     *
                     * While we changing the corePoolSize we need
                     * to stop running worker threads from accepting new
                     * tasks.
                     */
                        
                    //we need atomicity for the execute method.
                    executeLock.lock();
                    try {

                        pauseLock.lock();
                        try {
                            isPaused = true;
                        } finally {
                            pauseLock.unlock();
                        }
                            
                        setCorePoolSize(MAX_WORKER_THREADS);
                        super.execute(command);
                        setCorePoolSize(0);
                            
                        pauseLock.lock();
                        try {
                            isPaused = false;
                            unpaused.signalAll();
                        } finally {
                            pauseLock.unlock();
                        }
                    } finally {
                        executeLock.unlock();
                    }
                }
                @Override 
                protected void afterExecute(Runnable r, Throwable t) { 
                    super.afterExecute(r, t);
                    pauseLock.lock();
                    try {
                        while(isPaused) {
                            unpaused.await();
                        }
                    } catch(InterruptedException ignore) {
                            
                    } finally {
                        pauseLock.unlock();
                    }
                }
            };
    }
    return executorService; 
}

From source file:la2launcher.MainFrame.java

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
    final long initTime = new Date().getTime();
    ReentrantLock lock = new ReentrantLock();
    final String patcherUrl = "http://" + updateHost + "/hf//updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000)
    final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS,
            new ArrayBlockingQueue<Runnable>(10000));
    filesProcessed = 0;//from  w  ww.  j  a  v  a 2 s  . c  o m
    tpe.execute(new Runnable() {
        @Override
        public void run() {
            jTextArea2.setText("");
            DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
            jProgressBar1.setMinimum(0);
            jProgressBar1.setMaximum(model.getRowCount());
            jProgressBar1.setValue(0);
            jLabel4.setText("0/" + model.getRowCount());
            for (int i = 0; i < model.getRowCount(); i++) {
                boolean checked = (Boolean) model.getValueAt(i, 1);
                String fileName = (String) model.getValueAt(i, 0);
                if (checked) {
                    tpe.execute(new Runnable() {
                        @Override
                        public void run() {

                            final String fileUrl = "http://" + updateHost + "/hf/" + fileName.replace("\\", "/")
                                    + ".la2";
                            try {
                                printMsg("  " + fileUrl);
                                File file = new File(gamePath + fileName + ".rar");
                                File fileExt = new File(gamePath + fileName);

                                file.getParentFile().mkdirs();
                                FileOutputStream fos = new FileOutputStream(file);
                                CloseableHttpClient httpclient = HttpClients.createDefault();
                                HttpGet httpGet = new HttpGet(fileUrl);
                                CloseableHttpResponse response1 = httpclient.execute(httpGet);

                                HttpEntity entity1 = response1.getEntity();
                                copyStream(entity1.getContent(), fos, new CopyListener() {
                                    @Override
                                    public void transfered(int n) {
                                        bytesRecieved += n;
                                        bytesRecievedTotal += n;
                                    }
                                });
                                response1.close();
                                fos.close();

                                printMsg("?? : " + fileName);

                                lock.lock();
                                //fixBzip2File(file);
                                //printMsg(" ?");

                                extractArchive(file.getAbsolutePath());

                                //BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(file));
                                //OutputStream pout = new FileOutputStream(fileExt);
                                //copyStream(archStream, pout, null);
                                //pout.close();
                                //archStream.close();
                                //jTextArea2.setText(jTextArea2.getText() + "\r\n? : " + fileName);
                                printMsg("? : " + fileName);
                                //file.delete();

                                //                                    File tgt = new File(gamePath + fileName);
                                //                                    if (tgt.exists()) {
                                //                                        tgt.delete();
                                //                                    }
                                //tgt.getParentFile().mkdirs();
                                //Files.move(fileExt.toPath(), new File(gamePath + fileName).toPath());
                                //jTextArea2.setText(jTextArea2.getText() + "\r\n ??: " + fileName);
                                printMsg(" ??: " + fileName);
                                jProgressBar1.setIndeterminate(false);
                                jLabel4.setText((++filesProcessed) + "/" + model.getRowCount());
                                jProgressBar1.setValue((int) filesProcessed);
                                lock.unlock();
                            } catch (IOException ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (Exception ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    });
                }
            }
        }
    });

    jButton5.setEnabled(false);
    jButton6.setEnabled(false);
    jButton7.setEnabled(false);
    jButton8.setEnabled(false);
    jButton9.setEnabled(false);
    jButton10.setEnabled(false);
    jProgressBar1.setIndeterminate(true);
    new Thread() {
        @Override
        public void run() {
            do {
                long millis = new Date().getTime();
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                millis = new Date().getTime() - millis;
                BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0));
                totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING);
                jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : "
                        + totBig + " MB");
                bytesRecieved = 0;
            } while (tpe.getActiveCount() > 0);
            tpe.shutdown();
            jButton5.setEnabled(true);
            jButton6.setEnabled(true);
            jButton7.setEnabled(true);
            jButton8.setEnabled(true);
            jButton9.setEnabled(true);
            jButton10.setEnabled(true);
            jProgressBar1.setIndeterminate(false);
            printMsg("  " + (new Date().getTime() - initTime)
                    + " ?.");
        }
    }.start();
}