/** * Construct a new instance of the code <code>ExecutorService</code>, with its own underlying <code>NSOperationQueue</code> */ public DispatchExecutorService() { queue = NSOperationQueue.CLASS.alloc().init(); }
public void shutdown() { SecurityManager sm = System.getSecurityManager(); if(sm != null) { sm.checkPermission(shutdownPerm); } try { shutdownLock.lock(); state = State.SHUTDOWN; terminateIfDone(queue.operationCount().intValue() == 0); } finally { shutdownLock.unlock(); } }
/** * If the ExecutorService has been shutdown and the work queue is empty, * transition to the <code>TERMINATED</code> state. * * @param queueEmpty pass true if the queue is currently empty. */ private void terminateIfDone(boolean queueEmpty) { try { shutdownLock.lock(); if(state == State.SHUTDOWN && queueEmpty) { shutdownCondition.signalAll(); queue.setSuspended(true); state = State.TERMINATED; } } finally { shutdownLock.unlock(); } }
public List<Runnable> call() { try { shutdownLock.lock(); state = State.SHUTDOWN; NSArray queuedTasks = queue.operations(); List<Runnable> result = new ArrayList<Runnable>(queuedTasks.count()); for(int i = 0; i < queuedTasks.count(); i++) { NSOperation o = Rococoa.cast(queuedTasks.objectAtIndex(i), NSOperation.class); InvocationFutureTask<?> task = tasks.get(o.id()); if(task != null && !(o.isFinished() || o.isCancelled())) { result.add(task.getOriginalRunnable()); } } queue.cancelAllOperations(); tasks.clear(); terminateIfDone(queue.operationCount().intValue() == 0); return result; } finally { shutdownLock.unlock(); } } });
public void execute(Runnable command) { try { shutdownLock.lock(); if(state != State.RUNNING) { throw new RejectedExecutionException("Executor is not running"); } else { InvocationFutureTask<?> task = command instanceof InvocationFutureTask<?> ? (InvocationFutureTask<?>) command : (InvocationFutureTask<?>) newTaskFor(command, null); queue.addOperation(task.getInvocationOperation()); } } finally { shutdownLock.unlock(); } }
@Override public void run() { try { super.run(); } finally { tasks.remove(invocation.id()); if(state == State.SHUTDOWN) { //i.e. this is the last item on the queue terminateIfDone(queue.operationCount().intValue() <= 1); } } } }
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long wait = unit.toNanos(timeout); shutdownLock.lock(); try { while(!isTerminated()) { if(wait <= 0) { return false; } wait = shutdownCondition.awaitNanos(wait); terminateIfDone(queue.operationCount().intValue() == 0); } return true; } finally { shutdownLock.unlock(); } }