Skip to content
Snippets Groups Projects
PollingRemovableDriveMonitor.java 2.01 KiB
Newer Older
package org.briarproject.plugins.file;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;

class PollingRemovableDriveMonitor implements RemovableDriveMonitor, Runnable {

	private static final Logger LOG =
			Logger.getLogger(PollingRemovableDriveMonitor.class.getName());
	private final Executor ioExecutor;
	private final RemovableDriveFinder finder;
	private final long pollingInterval;

	private volatile boolean running = false;
	private volatile Callback callback = null;
	private final Lock pollingLock = new ReentrantLock();
	private final Condition stopPolling = pollingLock.newCondition();
	public PollingRemovableDriveMonitor(Executor ioExecutor,
			RemovableDriveFinder finder, long pollingInterval) {
		this.ioExecutor = ioExecutor;
		this.finder = finder;
		this.pollingInterval = pollingInterval;
	}

	public void start(Callback callback) throws IOException {
akwizgran's avatar
akwizgran committed
		this.callback = callback;
		running = true;
	public void stop() throws IOException {
akwizgran's avatar
akwizgran committed
		running = false;
		pollingLock.lock();
		try {
			stopPolling.signalAll();
		} 
		finally {
			pollingLock.unlock();
			Collection<File> drives = finder.findRemovableDrives();
				pollingLock.lock();
				try {
					stopPolling.await(pollingInterval, TimeUnit.MILLISECONDS);
				} 
				finally{
					pollingLock.unlock();
				Collection<File> newDrives = finder.findRemovableDrives();
				for(File f : newDrives) {
					if(!drives.contains(f)) callback.driveInserted(f);
		} catch(InterruptedException e) {
			LOG.warning("Interrupted while waiting to poll");
			Thread.currentThread().interrupt();
			callback.exceptionThrown(e);