Java Code Examples for java.util.Timer#purge()

The following examples show how to use java.util.Timer#purge() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RMManager.java    From cxf with Apache License 2.0 6 votes vote down vote up
void shutdownReliableEndpoint(Endpoint e) {
    RMEndpoint rme = reliableEndpoints.get(e);
    if (rme == null) {
        // not found
        return;
    }
    rme.shutdown();

    // remove references to timer tasks cancelled above to make them
    // eligible for garbage collection
    Timer t = getTimer(false);
    if (t != null) {
        t.purge();
    }

    reliableEndpoints.remove(e);
}
 
Example 2
Source File: RMManager.java    From cxf with Apache License 2.0 6 votes vote down vote up
@PreDestroy
public void shutdown() {
    // shutdown remaining endpoints
    if (!reliableEndpoints.isEmpty()) {
        LOG.log(Level.FINE,
                "Shutting down RMManager with {0} remaining endpoints.",
                new Object[] {Integer.valueOf(reliableEndpoints.size())});
        for (RMEndpoint rme : reliableEndpoints.values()) {
            rme.shutdown();
        }
    }

    // remove references to timer tasks cancelled above to make them
    // eligible for garbage collection
    Timer t = getTimer(false);
    if (t != null) {
        t.purge();
        t.cancel();
    }

    // unregistring of this managed bean from the server is done by the bus itself
}
 
Example 3
Source File: TimerTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testTaskNotCancelledWhenTimerCancelledAndPurged() throws Exception {
    final int timeSleeping = 200;
    Timer t = new Timer();
    final AtomicLong counter = new AtomicLong();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                counter.incrementAndGet();
                Thread.sleep(timeSleeping);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        }
    };
    t.scheduleAtFixedRate(task, 1 /* delay */, 100 /* rate */);
    Thread.sleep(1000);
    t.cancel();
    t.purge();
    // Returns true as the task wasn't cancelled before.
    assertTrue(task.cancel());
}
 
Example 4
Source File: ElasticSearchSink.java    From flume-elasticsearch-sink with Apache License 2.0 6 votes vote down vote up
/**
 * Checks for elasticsearch connection
 * Sets shouldBackOff to true if bulkProcessor failed to deliver the request.
 * Resets shouldBackOff to false once the connection to elasticsearch is established.
 */
public void assertConnection() {
    shouldBackOff.set(true);
    final Timer timer = new Timer();
    final TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                if (checkConnection()) {
                    shouldBackOff.set(false);
                    timer.cancel();
                    timer.purge();
                }
            } catch (IOException e) {
                logger.error("ping request for elasticsearch failed " + e.getMessage(), e);
            }
        }
    };
    timer.scheduleAtFixedRate(task, 0, CHECK_CONNECTION_PERIOD);
}
 
Example 5
Source File: BGMFader.java    From SchoolQuest with GNU General Public License v3.0 5 votes vote down vote up
public static void stop(final MediaPlayer mediaPlayer, int fadeDuration,
                        final Runnable... endRunnable) {
    if (fadeDuration > 0) { iVolume = INT_VOLUME_MAX; }
    else { iVolume = INT_VOLUME_MIN; }

    updateVolume(mediaPlayer, 0);

    if (fadeDuration > 0) {
        final Timer timer = new Timer(true);
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                updateVolume(mediaPlayer,-1);
                if (iVolume == INT_VOLUME_MIN) {
                    mediaPlayer.stop();
                    timer.cancel();
                    timer.purge();
                    if (endRunnable.length != 0) { endRunnable[0].run(); }
                }
            }
        };

        int delay = fadeDuration / INT_VOLUME_MAX;
        if (delay == 0) { delay = 1; }

        timer.schedule(timerTask, delay, delay);
    }
}
 
Example 6
Source File: BlurIndexSimpleWriter.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private Closeable makeCloseable(Timer timer, final TimerTask timerTask) {
  return new Closeable() {
    @Override
    public void close() throws IOException {
      timerTask.cancel();
      timer.purge();
    }
  };
}
 
Example 7
Source File: MonitorCommand.java    From LagMonitor with MIT License 5 votes vote down vote up
private void stopMonitor(CommandSender sender) {
    Timer timer = plugin.getMonitorTimer();
    if (monitorTask == null && timer == null) {
        sendError(sender, "Monitor is not running");
    } else {
        monitorTask = null;
        if (timer != null) {
            timer.cancel();
            timer.purge();
            plugin.setMonitorTimer(null);
        }

        sender.sendMessage(ChatColor.DARK_GREEN + "Monitor stopped");
    }
}
 
Example 8
Source File: LongPollingManager.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void removePollingChannelExpireTask(String uri) {
	Timer timer = pollingChannelExpireMap.remove(uri);
	if(timer != null) {
		int cnt = timer.purge();
		
		log.debug("removePollingChannelExpireTask] remove task count is {}", cnt);
	}
}
 
Example 9
Source File: MonitorCommand.java    From LagMonitor with MIT License 5 votes vote down vote up
private void stopMonitor(CommandSender sender) {
    Timer timer = plugin.getMonitorTimer();
    if (monitorTask == null && timer == null) {
        sendError(sender, "Monitor is not running");
    } else {
        monitorTask = null;
        if (timer != null) {
            timer.cancel();
            timer.purge();
            plugin.setMonitorTimer(null);
        }

        sender.sendMessage(ChatColor.DARK_GREEN + "Monitor stopped");
    }
}
 
Example 10
Source File: LongPollingManager.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void removePollingChannelExpireTask(String uri) {
	Timer timer = pollingChannelExpireMap.remove(uri);
	if(timer != null) {
		int cnt = timer.purge();
		
		log.debug("removePollingChannelExpireTask] remove task count is {}", cnt);
	}
}
 
Example 11
Source File: BaseCloneableBootstrapContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Shutdown
 */
public void shutdown()
{
   if (timers != null)
   {
      for (Timer t : timers)
      {
         t.cancel();
         t.purge();
      }
   }
}
 
Example 12
Source File: RunTasksModel.java    From AlipayOrdersSupervisor-GUI with MIT License 5 votes vote down vote up
/**
 * 停止当前任务(只会由button UI触发, 肯定为当前选中task)
 */
public void StopTask() {
    this.taskListModel.MarkTaskStatus(currentSelectTask.id, TaskStatus.STOPPED);
    NotifyAllObservers();

    // 停止定时抓取任务
    Timer timer = ApsvTimerManager.GetTimer(currentSelectTask.id);
    if (timer != null) {
        timer.cancel();
        timer.purge();
    }
    ApsvTimerManager.ClearStartTime(currentSelectTask.id);
}
 
Example 13
Source File: BGMFader.java    From SchoolQuest with GNU General Public License v3.0 5 votes vote down vote up
public static void start(final MediaPlayer mediaPlayer, int fadeDuration) {
    if (fadeDuration > 0) { iVolume = INT_VOLUME_MIN; }
    else { iVolume = INT_VOLUME_MAX; }

    updateVolume(mediaPlayer, 0);

    if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); }

    if (fadeDuration > 0) {
        final Timer timer = new Timer(true);
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                updateVolume(mediaPlayer, 1);
                if (iVolume == INT_VOLUME_MAX) {
                    timer.cancel();
                    timer.purge();
                }
            }
        };

        int delay = fadeDuration / INT_VOLUME_MAX;
        if (delay == 0) { delay = 1; }

        timer.schedule(timerTask, delay, delay);
    }
}
 
Example 14
Source File: LagMonitor.java    From LagMonitor with MIT License 4 votes vote down vote up
private void close(Timer timer) {
    if (timer != null) {
        timer.cancel();
        timer.purge();
    }
}
 
Example 15
Source File: Owl2VowlController.java    From OWL2VOWL with MIT License 4 votes vote down vote up
public void timed_provideMemoryReleaseHintForGC(String sessionId, String msg, Timer t ) {
	t.cancel();
	t.purge();
	t=null;
	provideMemoryReleaseHintForGC(sessionId, msg);
}
 
Example 16
Source File: LagMonitor.java    From LagMonitor with MIT License 4 votes vote down vote up
private void close(Timer timer) {
    if (timer != null) {
        timer.cancel();
        timer.purge();
    }
}
 
Example 17
Source File: DownloadInfoRunnable.java    From aptoide-client with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void run() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Timer timer = new Timer();

    try {

        for (DownloadModel downloadModel : mFilesToDownload) {
            DownloadThread thread = new DownloadThread(downloadModel, this);
            executor.submit(thread);
            threads.add(thread);
        }

        checkDirectorySize(Aptoide.getConfiguration().getPathCacheApks());

        mSize = getAllThreadSize();

        TimerTask task = new TimerTask() {

            public long mAvgSpeed;
            /** How much was downloaded last time. */
            private long iMLastDownloadedSize = mDownloadedSize;
            /** The nanoTime last time. */
            private long iMLastTime = System.currentTimeMillis();
            private long iMFirstTime = System.currentTimeMillis();

            @Override
            public void run() {
                long mReaminingSize = getAllSizeRemaining();
                mDownloadedSize = getAllDownloadedSize();
                mProgress = getAllProgress();

                long timeElapsedSinceLastTime = System.currentTimeMillis() - iMLastTime;
                long timeElapsed = System.currentTimeMillis() - iMFirstTime;
                iMLastTime = System.currentTimeMillis();
                // Difference between last time and this time = how much was downloaded since last run.
                long downloadedSinceLastTime = mDownloadedSize - iMLastDownloadedSize;
                iMLastDownloadedSize = mDownloadedSize;
                if (timeElapsedSinceLastTime > 0 && timeElapsed > 0) {
                    // Speed (bytes per second) = downloaded bytes / time in seconds (nanoseconds / 1000000000)
                    mAvgSpeed = (mDownloadedSize) * 1000 / timeElapsed;
                    mSpeed = downloadedSinceLastTime * 1000 / timeElapsedSinceLastTime;
                }


                if (mAvgSpeed > 0) {
                    // ETA (milliseconds) = remaining byte size / bytes per millisecond (bytes per second * 1000)
                    mETA = (mReaminingSize - mDownloadedSize) * 1000 / mAvgSpeed;
                }
                Log.d("DownloadManager", "ETA: " + mETA + " Speed: " + mSpeed / 1000 + " Size: " + DownloadUtils.formatBytes(mSize) + " Downloaded: " + DownloadUtils.formatBytes(mDownloadedSize) + " Status: " + mStatusState + " TotalDownloaded: " + DownloadUtils.formatBytes(mProgress) + " " + System.identityHashCode(DownloadInfoRunnable.this));

                download.setSpeed(getSpeed());
                download.setTimeLeft(mETA);
                download.setProgress(getPercentDownloaded());
                BusProvider.getInstance().post(new OttoEvents.DownloadInProgress(download));
            }
        };

        // Schedule above task for every (UPDATE_INTERVAL_MILLISECONDS) milliseconds.
        timer.schedule(task, 0, UPDATE_INTERVAL_MILLISECONDS);
        executor.shutdown();
        // Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs,
        // or the current thread is interrupted, whichever happens first.
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

        timer.cancel();
        timer.purge();
        mSize = getAllThreadSize();
        mProgress = getAllProgress();

        Log.d("download-trace", "Downloads done " + mSize + " " + mProgress + " " + mStatusState.getEnumState().name());
        download.setSpeed(getSpeed());
        download.setProgress(getPercentDownloaded());

        if (mStatusState instanceof ActiveState) {
            changeStatusState(new CompletedState(this));
            autoExecute();
            Analytics.DownloadComplete.downloadComplete(download);
        }

    } catch (Exception e) {
        changeStatusState(new ErrorState(this, EnumDownloadFailReason.NO_REASON));
        e.printStackTrace();
    }

    BusProvider.getInstance().post(new OttoEvents.DownloadEvent(getId(), mStatusState));

    downloadManager.updatePendingList();
    threads.clear();
    mDownloadedSize = 0;
    mSpeed = 0;
    mETA = 0;

    Logger.d("download-trace", "Download Finish??" + download.getName());
}
 
Example 18
Source File: TimerTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testTimerCancelledAfterExceptionAndTasksNotCancelledAfterPurge() throws Exception {
    UncaughtExceptionHandler excHandler = Thread.getDefaultUncaughtExceptionHandler();
    // Install an uncaught exception handler because we are
    // deliberately causing the timer thread to die in this test (which will cause CTS tests
    // to fail).
    SwallowUncaughtExceptionHandler swallowUncaughtExceptionHandler =
            new SwallowUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(swallowUncaughtExceptionHandler);
    try {
        Timer t = new Timer();
        final AtomicLong counter = new AtomicLong();

        // Schedule tasks to run:
        // A) {In 1 millis} Increment a counter by 1 and throw an exception
        // B) {In 100 millis} Increment a counter by 1000 (but it's not intended to be executed
        //        because of the previous exception).
        // We want A and B to be scheduled before A runs.
        // We add them in reverse order.
        // We have ~99 millis after scheduling B to schedule A. If A ran before we scheduled B
        // we would get an exception when we came to schedule B.

        TimerTask taskThatDoesntThrow = new IncrementCounterTaskAndPossiblyThrowAfter(
                counter,
                1000, /* incrementAmount */
                false /* willThrow */);
        TimerTask taskThatThrows = new IncrementCounterTaskAndPossiblyThrowAfter(
                counter,
                1,    /* incrementAmount */
                true  /* willThrow */);
        t.schedule(taskThatDoesntThrow, 100 /* delay */);
        t.scheduleAtFixedRate(taskThatThrows, 1 /* delay */, 100 /* period */);
        swallowUncaughtExceptionHandler.waitForException(1000);
        // Check the counter wasn't increased more than once (ie, the exception killed the
        // execution thread).
        assertEquals("Counter should be 1, and is: " + counter.get(), 1, counter.get());
        t.purge();
        assertTrue("The timer should not cancel the tasks", taskThatDoesntThrow.cancel());
        assertTrue("The timer should not cancel the tasks", taskThatThrows.cancel());

        TimerTask otherTask = new TimerTask() {
            @Override
            public void run() {
                counter.incrementAndGet();
            }
        };

        try {
            t.schedule(otherTask, 1);
            fail("Timer should be cancelled and no new tasks should be allowed");
        } catch (Exception expected) {
            // Expected.
        }
    } finally {
        Thread.setDefaultUncaughtExceptionHandler(excHandler);
    }
}
 
Example 19
Source File: Downloader.java    From fdroidclient with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This copies the downloaded data from the InputStream to the OutputStream,
 * keeping track of the number of bytes that have flowed through for the
 * progress counter.
 */
private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)
        throws IOException, InterruptedException {
    Timer timer = new Timer();
    try {
        bytesRead = 0;
        totalBytes = totalDownloadSize();
        byte[] buffer = new byte[bufferSize];

        timer.scheduleAtFixedRate(progressTask, 0, 100);

        // Getting the total download size could potentially take time, depending on how
        // it is implemented, so we may as well check this before we proceed.
        throwExceptionIfInterrupted();

        while (true) {

            int count;
            if (input.available() > 0) {
                int readLength = Math.min(input.available(), buffer.length);
                count = input.read(buffer, 0, readLength);
            } else {
                count = input.read(buffer);
            }

            throwExceptionIfInterrupted();

            if (count == -1) {
                Utils.debugLog(TAG, "Finished downloading from stream");
                break;
            }
            bytesRead += count;
            output.write(buffer, 0, count);
        }
    } finally {
        downloaderProgressListener = null;
        timer.cancel();
        timer.purge();
        output.flush();
        output.close();
    }
}
 
Example 20
Source File: KettleBeamPipelineExecutor.java    From kettle-beam with Apache License 2.0 4 votes vote down vote up
private PipelineResult executePipeline() throws KettleException {
  ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
  try {
    // Explain to various classes in the Beam API (@see org.apache.beam.sdk.io.FileSystems)
    // what the context classloader is.
    // Set it back when we're done here.
    //
    Thread.currentThread().setContextClassLoader( classLoader );

    final Pipeline pipeline = getPipeline( transMeta, jobConfig );

    logChannel.logBasic( "Creation of Apache Beam pipeline is complete. Starting execution..." );

    // This next command can block on certain runners...
    //
    PipelineResult pipelineResult = asyncExecutePipeline(pipeline);

    Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
      @Override public void run() {

        // Log the metrics...
        //
        if ( isLoggingMetrics() ) {
          logMetrics( pipelineResult );
        }

        // Update the listeners.
        //
        updateListeners( pipelineResult );
      }
    };
    // Every 5 seconds
    //
    timer.schedule( timerTask, 5000, 5000 );

    // Wait until we're done
    //
    pipelineResult.waitUntilFinish();

    timer.cancel();
    timer.purge();

    // Log the metrics at the end.
    logMetrics( pipelineResult );

    // Update a last time
    //
    updateListeners( pipelineResult );

    logChannel.logBasic( "  ----------------- End of Beam job " + pipeline.getOptions().getJobName() + " -----------------------" );

    return pipelineResult;
  } catch(Exception e) {
    throw new KettleException( "Error building/executing pipeline", e );
  } finally {
    Thread.currentThread().setContextClassLoader( oldContextClassLoader );
  }

}