From 7444c2b1f281b5b147717ba2a2ed6798c66a057b Mon Sep 17 00:00:00 2001 From: Keuin Date: Mon, 27 Apr 2020 17:42:07 +0800 Subject: Resized the logo to reduce plugin size. Refactored code for a better implementation of async and blocking task. --- .../abstracts/AbstractAsyncOperation.java | 53 ++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractAsyncOperation.java (limited to 'src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractAsyncOperation.java') diff --git a/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractAsyncOperation.java b/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractAsyncOperation.java new file mode 100644 index 0000000..f1a19de --- /dev/null +++ b/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractAsyncOperation.java @@ -0,0 +1,53 @@ +package com.keuin.kbackupfabric.operation.abstracts; + +public abstract class AbstractAsyncOperation extends AbstractSerializedOperation { + + private final Thread thread; + private final String name; + private final Object sync = new Object(); + + protected AbstractAsyncOperation(String name) { + this.name = name; + this.thread = new Thread(this::async, name); + } + + /** + * Start the worker thread. + * + * @return true if succeed starting, false if already started. + */ + @Override + protected final boolean operate() { + synchronized (sync) { + if (thread.isAlive()) + return false; + if (!sync()) + return false; + thread.start(); + return true; + } + } + + /** + * Implement your async operation here. + * When this method returns, the operation must finish. + */ + protected abstract void async(); + + /** + * If necessary, implement your sync operations here. + * It will be invoked before starting the async thread. + */ + protected boolean sync() { + return true; + } + + public final String getName() { + return name; + } + + @Override + public String toString() { + return "operation " + name; + } +} -- cgit v1.2.3