Suppose you have a method called in many places and whose call you want to make parallel. This can be done without changing the method call code and the code of the method itself. You only need to create an extension of the enclosing class, and change the code for creating the object.
It was:
class Service { public void longJob(Object arg) {...} } ... Service s=new Service(); ... s.longJob(arg);
It became:
class Service { public void longJob(Object arg) {...} } class ServiceWrapper extends Service { ... } ... Service s=new ServiceWrapper() ; ... s.longJob(arg);
')
The main improvement consists in redefining the parallelizable method:
class ServiceWrapper extends Service { SerialExecutor executor=new SerialExecutor(trueExecutor); public void longJob(final Object arg) { executor.execute(new Runnable() { public void run() { ServiceWrapper.super.longJob(arg); } }); } }
SerialExecutor can be obtained from the documentation on
java.util.concurrent.Executor . Optimized version - in my
github.com/rfqu/CodeSamples . It performs the tasks submitted to it sequentially, thereby eliminating the need to introduce synchronization into the longJob () method: all calls to this method will be executed in turn. If there are several public methods in the Service class, all of them must be redefined in the same way, and all of them will be executed sequentially, from the same queue.
Of course, this method is not always applicable and does not solve all problems. For example, larger edits will be required if the method returns a value, or if one public method invokes another public multithreaded method.
The override idea is from
Project Lombok .