List of usage examples for java.lang Thread interrupt
public void interrupt()
From source file:com.comic.lazyupload.image.PhotoManager.java
/** * Stops a download Thread and removes it from the threadpool * //w w w . java2 s .c om * @param downloaderTask * The download task associated with the Thread * @param pictureURL * The URL being downloaded */ static public void removeDownload(PhotoTask downloaderTask, URL pictureURL) { // If the Thread object still exists and the download matches the // specified URL if (downloaderTask != null && downloaderTask.getImageURL().equals(pictureURL)) { /* * Locks on this class to ensure that other processes aren't * mutating Threads. */ synchronized (sInstance) { // Gets the Thread that the downloader task is running on Thread thread = downloaderTask.getCurrentThread(); // If the Thread exists, posts an interrupt to it if (null != thread) thread.interrupt(); } /* * Removes the download Runnable from the ThreadPool. This opens a * Thread in the ThreadPool's work queue, allowing a task in the * queue to start. */ sInstance.mDownloadThreadPool.remove(downloaderTask.getHTTPDownloadRunnable()); } }
From source file:de.dal33t.powerfolder.PowerFolder.java
/** * Starts a PowerFolder controller with the given command line arguments * * @param args//from ww w .ja va2s. c o m */ public static void startPowerFolder(String[] args) { // Touch Logger immediately to initialize handlers. LoggingManager.isLogToFile(); // Default exception logger Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { e.printStackTrace(); log.log(Level.SEVERE, "Exception in " + t + ": " + e.toString(), e); } }); CommandLine commandLine = parseCommandLine(args); if (commandLine == null) { return; } // -l --log console log levels (severe, warning, info, fine and finer). if (commandLine.hasOption("l")) { String levelName = commandLine.getOptionValue("l"); Level level = LoggingManager.levelForName(levelName); if (level != null) { LoggingManager.setConsoleLogging(level); } } if (commandLine.hasOption("s")) { // Server mode, suppress debug output on console // Logger.addExcludeConsoleLogLevel(Logger.DEBUG); } if (commandLine.hasOption("h")) { // Show help HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("PowerFolder", COMMAND_LINE_OPTIONS); return; } int rconPort = Integer.valueOf(ConfigurationEntry.NET_RCON_PORT.getDefaultValue()); String portStr = commandLine.getOptionValue("k"); if (StringUtils.isNotBlank(portStr)) { try { rconPort = Integer.valueOf(portStr.trim()); } catch (Exception e) { log.warning("Unable to parse rcon port: " + portStr + ". " + e); } } boolean runningInstanceFound = RemoteCommandManager.hasRunningInstance(rconPort); if (commandLine.hasOption("k")) { if (runningInstanceFound) { System.out.println("Stopping " + NAME); // Send quit command RemoteCommandManager.sendCommand(rconPort, RemoteCommandManager.QUIT); } else { System.err.println("Process not running"); } // stop return; } // set language from commandline to preferences if (commandLine.hasOption("g")) { Preferences.userNodeForPackage(Translation.class).put("locale", commandLine.getOptionValue("g")); } if (JavaVersion.systemVersion().isOpenJDK()) { Object[] options = { "Open Oracle home page and exit", "Exit" }; int n = JOptionPane.showOptionDialog(null, "You are using OpenJDK which is unsupported.\n" + "Please install the client with bundled JRE or install the Oracle JRE", "Unsupported JRE", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (n == 0) { try { BrowserLauncher.openURL("http://www.java.com"); } catch (IOException e1) { e1.printStackTrace(); } } return; } // The controller. Controller controller = Controller.createController(); String[] files = commandLine.getArgs(); // Parsing of command line completed boolean commandContainsRemoteCommands = files != null && files.length >= 1 || commandLine.hasOption("e") || commandLine.hasOption("r") || commandLine.hasOption("a"); // Try to start controller boolean startController = !commandContainsRemoteCommands || !runningInstanceFound; try { log.info("PowerFolder v" + Controller.PROGRAM_VERSION); // Start controller if (startController) { controller.startConfig(commandLine); } // Send remote command if there a files in commandline if (files != null && files.length > 0) { // Parse filenames and build remote command StringBuilder openFilesRCommand = new StringBuilder(RemoteCommandManager.OPEN); for (String file : files) { openFilesRCommand.append(file); // FIXME: Add ; separator ? } // Send remote command to running PowerFolder instance RemoteCommandManager.sendCommand(openFilesRCommand.toString()); } if (commandLine.hasOption("e")) { RemoteCommandManager.sendCommand(RemoteCommandManager.MAKEFOLDER + commandLine.getOptionValue("e")); } if (commandLine.hasOption("r")) { RemoteCommandManager .sendCommand(RemoteCommandManager.REMOVEFOLDER + commandLine.getOptionValue("r")); } if (commandLine.hasOption("a")) { RemoteCommandManager.sendCommand(RemoteCommandManager.COPYLINK + commandLine.getOptionValue("a")); } } catch (Throwable t) { t.printStackTrace(); log.log(Level.SEVERE, "Throwable", t); return; } // Begin monitoring memory usage. if (controller.isStarted() && controller.isUIEnabled()) { ScheduledExecutorService service = controller.getThreadPool(); service.scheduleAtFixedRate(new MemoryMonitor(controller), 1, 1, TimeUnit.MINUTES); } // Not go into console mode if ui is open if (!startController) { if (runningInstanceFound) { RemoteCommandManager.sendCommand(RemoteCommandManager.SHOW_UI); } return; } System.out.println("------------ " + NAME + " " + Controller.PROGRAM_VERSION + " started ------------"); boolean restartRequested = false; do { // Go into restart loop while (controller.isStarted() || controller.isShuttingDown()) { try { Thread.sleep(500); } catch (InterruptedException e) { log.log(Level.WARNING, "InterruptedException", e); return; } } restartRequested = controller.isRestartRequested(); if (restartRequested) { Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces(); for (Thread thread : threads.keySet()) { if (thread.getName().startsWith("PoolThread") || thread.getName().startsWith("Reconnector") || thread.getName().startsWith("ConHandler")) { thread.interrupt(); } } log.info("Restarting controller"); System.out.println( "------------ " + NAME + " " + Controller.PROGRAM_VERSION + " restarting ------------"); controller = null; System.gc(); controller = Controller.createController(); // Start controller controller.startConfig(commandLine); } } while (restartRequested); }
From source file:com.comic.lazyupload.image.PhotoManager.java
/** * Cancels all Threads in the ThreadPool *//*w w w .j a va2 s . c o m*/ public static void cancelAll() { /* * Creates an array of tasks that's the same size as the task work queue */ PhotoTask[] taskArray = new PhotoTask[sInstance.mDownloadWorkQueue.size()]; // Populates the array with the task objects in the queue sInstance.mDownloadWorkQueue.toArray(taskArray); // Stores the array length in order to iterate over the array int taskArraylen = taskArray.length; /* * Locks on the singleton to ensure that other processes aren't mutating * Threads, then iterates over the array of tasks and interrupts the * task's current Thread. */ synchronized (sInstance) { // Iterates over the array of tasks for (int taskArrayIndex = 0; taskArrayIndex < taskArraylen; taskArrayIndex++) { // Gets the task's current thread Thread thread = taskArray[taskArrayIndex].mThreadThis; // if the Thread exists, post an interrupt to it if (null != thread) { thread.interrupt(); } } } }
From source file:com.mobicomkit.api.attachment.AttachmentManager.java
/** * Cancels all Threads in the ThreadPool *///from w w w. ja v a2 s . co m public static void cancelAll() { /* * Creates an array of tasks that's the same size as the task work queue */ AttachmentTask[] taskArray = new AttachmentTask[sInstance.mDownloadWorkQueue.size()]; // Populates the array with the task objects in the queue sInstance.mDownloadWorkQueue.toArray(taskArray); // Stores the array length in order to iterate over the array int taskArraylen = taskArray.length; /* * Locks on the singleton to ensure that other processes aren't mutating Threads, then * iterates over the array of tasks and interrupts the task's current Thread. */ synchronized (sInstance) { // Iterates over the array of tasks for (int taskArrayIndex = 0; taskArrayIndex < taskArraylen; taskArrayIndex++) { // Gets the task's current thread Thread thread = taskArray[taskArrayIndex].mThreadThis; // if the Thread exists, post an interrupt to it if (null != thread) { thread.interrupt(); } } } }
From source file:com.applozic.mobicomkit.api.attachment.AttachmentManager.java
/** * Cancels all Threads in the ThreadPool *///w ww. j a v a 2 s.c o m public static void cancelAll() { /* * Creates an array of tasks that's the same size as the task work queue */ AttachmentTask[] taskArray = new AttachmentTask[sInstance.mDownloadWorkQueue.size()]; // Populates the array with the task objects in the queue sInstance.mDownloadWorkQueue.toArray(taskArray); // Stores the array length in order to iterate over the array int taskArraylen = taskArray.length; /* * Locks on the singleton to ensure that other processes aren't mutating Threads, then * iterates over the array of tasks and interrupts the task's current Thread. */ synchronized (sInstance) { // Iterates over the array of tasks for (AttachmentTask aTaskArray : taskArray) { // Gets the task's current thread Thread thread = aTaskArray.mThreadThis; // if the Thread exists, post an interrupt to it if (null != thread) { thread.interrupt(); } } } }
From source file:com.applozic.mobicomkit.api.attachment.AttachmentManager.java
/** * Stops a download Thread and removes it from the threadpool * * @param downloaderTask The download task associated with the Thread *///from www . ja v a 2 s. c om static public void removeDownload(AttachmentTask downloaderTask) { // If the Thread object still exists and the download matches the specified URL if (downloaderTask != null) { /* * Locks on this class to ensure that other processes aren't mutating Threads. */ synchronized (sInstance) { // Gets the Thread that the downloader task is running on Thread thread = downloaderTask.getCurrentThread(); // If the Thread exists, posts an interrupt to it if (null != thread) { thread.interrupt(); } else { Log.i(TAG, "Thread is coming null"); } } /* * Removes the download Runnable from the ThreadPool. This opens a Thread in the * ThreadPool's work queue, allowing a task in the queue to start. */ sInstance.mDownloadThreadPool.remove(downloaderTask.getHTTPDownloadRunnable()); } }
From source file:io.teak.sdk.TeakNotification.java
static void cancel(Context context, int platformId) { if (notificationManager == null) { try {//from w w w. j av a 2 s. c o m notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); } catch (Exception e) { Log.e(LOG_TAG, Log.getStackTraceString(e)); return; } } if (Teak.isDebug) { Log.d(LOG_TAG, "Canceling notification id: " + platformId); } notificationManager.cancel(NOTIFICATION_TAG, platformId); context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); Thread updateThread = TeakNotification.notificationUpdateThread.get(platformId); if (updateThread != null) { updateThread.interrupt(); } }
From source file:es.darkhogg.hazelnutt.Hazelnutt.java
/** * Terminates the application in at most <i>time</i> milliseconds for * every alive thread. /*from w w w. j a va 2 s . co m*/ * * @param time Number of milliseconds to wait for each thread to terminate */ public static void terminate(long time) { Logger logger = getLogger(); logger.info("Terminating application..."); try { getFrame().dispose(); // Get the root thread group ThreadGroup rootThreadGroup = Thread.currentThread().getThreadGroup(); while (rootThreadGroup.getParent() != null) { rootThreadGroup = rootThreadGroup.getParent(); } // Declare some collections Queue<ThreadGroup> threadGroups = new LinkedList<ThreadGroup>(); Queue<Thread> threads = new LinkedList<Thread>(); // Get ALL groups threadGroups.add(rootThreadGroup); while (!threadGroups.isEmpty()) { ThreadGroup group = threadGroups.remove(); Thread[] subThreads = new Thread[group.activeCount() * 2]; //group.enumerate( subThreads ); for (Thread subThread : subThreads) { if (subThread != null) { threads.add(subThread); } } ThreadGroup[] subThreadGroups = new ThreadGroup[group.activeGroupCount() * 2]; for (ThreadGroup subThreadGroup : subThreadGroups) { if (subThreadGroup != null) { threadGroups.add(subThreadGroup); } } } // Join a maximum of time milliseconds for all non-daemon threads while (!threads.isEmpty()) { Thread thread = threads.remove(); LOGGER.trace(thread); if (!thread.isDaemon() && thread != Thread.currentThread()) { logger.trace("Waiting for thread '" + thread.getName() + "'"); thread.join(time); if (thread.isAlive()) { logger.trace("Interrupting thread '" + thread.getName() + "'"); thread.interrupt(); } } } } catch (Throwable e) { LOGGER.warn("Interrupted while terminating application", e); } finally { // Exit the program System.exit(0); } }
From source file:org.devtcg.five.provider.FiveSyncAdapter.java
/** * Issue an HTTP GET request and store the result in a content provider. * Also triggers an update to <code>localFeedItemUri</code>, storing * <code>localUri</code> in <code>columnToUpdate</code>. *//*from w w w . ja v a 2s. c om*/ private static void downloadFileAndUpdateProvider(SyncContext context, AbstractSyncProvider serverDiffs, String httpUrl, Uri localUri, Uri localFeedItemUri, String columnToUpdate) throws IOException { if (context.hasError() || context.hasCanceled()) return; final HttpGet request = new HttpGet(httpUrl); final Thread currentThread = Thread.currentThread(); context.trigger = new CancelTrigger() { public void onCancel() { request.abort(); currentThread.interrupt(); } }; try { downloadFileAndUpdateProviderCancelable(context, serverDiffs, request, localUri, localFeedItemUri, columnToUpdate); } finally { context.trigger = null; } }
From source file:org.glassfish.tyrus.tests.qa.tools.Misc.java
public static void delete(final File path, final long timeout) throws InterruptedException { final CountDownLatch timer = new CountDownLatch(1); Thread worker = new Thread() { @Override//from w w w. j a v a 2s . co m public void run() { try { for (;;) { if (path.delete()) { timer.countDown(); break; } else { logger.log(Level.SEVERE, "Delete did not succeded for {0}", path.toString()); Thread.sleep(timeout * 10); // 100 tries } } } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); } } }; worker.start(); timer.await(timeout, TimeUnit.SECONDS); if (timer.getCount() > 0) { worker.interrupt(); throw new RuntimeException( String.format("Delete of %s failed after %d secs!", path.toString(), timeout)); } }