001package com.mrivanplays.process; 002 003/** 004 * Represents a process that's going to be run. 005 * 006 * @since 0.0.1 007 * @author <a href="mailto:ivan@mrivanplays.com">Ivan Pekov</a> 008 */ 009public abstract class Process { 010 011 /** 012 * Creates a new {@code Process} from a {@link Runnable} 013 * 014 * @param runnable input runnable 015 * @return process 016 */ 017 public static Process fromRunnable(Runnable runnable) { 018 return new Process() { 019 @Override 020 protected void run() { 021 runnable.run(); 022 } 023 }; 024 } 025 026 /** 027 * Main logic for running this process. 028 * 029 * @throws Throwable if anything goes wrong, the implementation can throw any exception. 030 */ 031 protected abstract void run() throws Throwable; 032 033 // =============================================== 034 private int processNum; 035 036 final void processNum(int processNum) { 037 this.processNum = processNum; 038 } 039 040 final void runProcess(ProcessesCompletion completion) { 041 try { 042 this.run(); 043 } catch (Throwable error) { 044 completion.countDownWithError(new ProcessException("in Process #" + this.processNum, error)); 045 return; 046 } 047 completion.countDown(); 048 } 049 050}