I have the following Foo class that uses FooProcessor class. So what i want to do is, while running cp1 instance process method, in parallel I want to run cp2.process().
public class Foo {
public static void main(String [] args){
FooProcessor cp1 = new FooProcessor();
FooProcessor cp2 = new FooProcessor();
cp1.process();
// in parallel process cp2.process();
}
}
public class FooProcessor {
public void process(){
System.out.println("Processing..");
}
}
However, i want cp1 sequentially, so i want it to run and complete, if cp2 doesnt complete or fails it is fine. If it doenst fail i want to join the results. It is not returning anything in this sample but I want to return result.
For this purpose, should is use TaskExecutor? or Thread?
I want only cp2 to run in parallel to cp1. or if i add more lets say cp3, i want that to run in parallel as well to cp1.
The way I would implement it, in summary :
run your different processes via an ExecutorService, for example ExecutorService executor = Executors.newFixedThreadPool(nThreads);
store the Futures of all your tasks in a List (returned by ExecutorService#submit)
wait for future1.get() to complete, where future1 is the future linked to cp1
once get returns (cp1 has finished) cancel all the other futures, (or shutdownNow the executor service if you don't need the executor any longer)
for that cancellation process to work, your cp2, cp3 etc need to implement an interruption policy that makes them stop what they are doing asap.
Thread would be a good choice...Something like a method that accepts a new threads and start them...
According to https://stackoverflow.com/a/2269177/454167,
You can use something like a AsyncTaskExecutor[1], which returns a Future object. You can then wait on the Future to know if cp2 returns success.
[1] http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/core/task/AsyncTaskExecutor.html#submit%28java.lang.Runnable%29
You can of course use plain and simple Threads
If you know you need to add more methods to the processor class, and for a given instance of it to keep execution order - let's say you first run method foo, and then run method bar, and you want them to run asynchronously, but keep execution order (first foo, then bar), I would consider to use Active Object pattern.
I recommend also using this approach because for the user of the processor class it will hide implementation details.
In addition, consider providing a decorator/wrapper that will provide this async ability to your objects - this way you will be able to control which object is run asynchronously and which isn't, and you will not have to "pollute" your Processor class with code needed for asynchronous invocation.
An example of usage in this case will be -
AsyncProcessor ap = new AsyncProcessor(p1);
ap.process(); //executed asynchronously
Proccessor p2 = new Processor();
p2.process(); //executed synchronously
Another apporach is to use as you mentioned, an executor -
This can be achieved by implementing a thread pool and pushing "execution units to it".
An execution unit will contain the target object (cp1, cp2, ...) and the method to execute (currently - only process)
The threads will take "an execution unit" from the queue and run them.
The implementation is similar to active object, but the "interface" for the user is different as it uses a "TaskExecutor" class to provide it "execution units"
If you're writing your own standalone application, using threads might be the easiest way forward. If you're in a Java EE environment, you should not create your own Thread objects, but use some other mechanism (such as sending messages and have message listeners process the signals you send). This is to have the Java EE container control resource utilization such as thread pools.
Example of using Threads:
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
executeSomeCodeInP1();
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
executeSomeCodeInP2();
}
});
t1.start();
t2.start();
// if you want to wait for both threads to finish before moving on,
// "join" the current thread
t1.join();
t2.join();
Related
currently I am experimenting with Concurrency in Java/JavaFX. Printing must run in a different thread otherwise it will make the JavaFX main thread freeze for a couple seconds. Right now my printing is done with this simplified example.
public void print(PrintContent pt) {
setPrintContent(pt);
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run() {
// send content to printer
}
With this code I am sending many print jobs parallel to my printer. Therefore I get the error telling me that my printer can only handle 1 print job at a time. Since I know that Threads cannot be reused, I would like to know if there is a possibility to queue up Threads, so that my printer only handles one print job at a time.
Thank you very much for your effort and your time.
Use a single threaded executor to execute the print jobs. It will create one (and only one) background thread and queue the jobs:
// it might be better not to make this static; but you need to ensure there is
// only one instance of this executor:
private static final Executor PRINT_QUEUE = Executors.newSingleThreadExecutor();
// ...
public void print(PrintContent pt) {
PRINT_QUEUE.execute(() -> {
// send content to printer
});
}
~~> WAY 1
You can implement your own BlockingQueue read this is very useful or use a default implementation from Java libraries tutorial
So after reading the above links,you add a method in your class like
public void addJob(Object job){
queue.put(job);
}
Secondly you implement a Thread that is running into an infinite while loop.Inside it you call the method
queue.take();
When the queue is empty this Thread is blocked waiting until a new Object is added,so you dont have to worry about spending cpu time.
Finally you can set some upper bounds so for example queue can contain .. 27 items.
Mention that in case of Thread failure you have to recreate it manually.
~~>WAY 2 Better Approach
You can use an Executors Interface:
ExecutorService executorService1 = Executors.newSingleThreadExecutor();
From documentation:
Creates an Executor that uses a single worker thread operating off an
unbounded queue. (Note however that if this single thread terminates
due to a failure during execution prior to shutdown, a new one will
take its place if needed to execute subsequent tasks.) Tasks are
guaranteed to execute sequentially, and no more than one task will be
active at any given time.
With the method below you retrieve a result if the job has successfully done.
Future future = executorService.submit(new Callable(){ public Object call() throws Exception { System.out.println("Asynchronous Callable"); return "Callable Result"; } });
System.out.println("future.get() = " + future.get());
If future.get() returns null, the job has been done successfully.
Remember to call
executorService.shutdown(); because the active threads inside this ExecutorService may prevent the JVM from shutting down.
Full tutorial here
I have a class Prefs, which has various methods. I need to rewrite it using threading and synchronization.
I'm looking at this variant: http://tutorials.jenkov.com/java-concurrency/synchronized.html
So currently:
class T_readConfigFile extends Thread {
protected Prefs p = null;
public T_readConfigFile(Prefs p) {
this.p =p;
}
public void run() {
p.readConfigFile();
}
}
and
public synchronized void readConfigFile() { ...
But somehow making N identical classes for each of the methods I want to thread doesn't look like a good idea. I assume it the entire class in this.p = p; gets loaded into memory — do I really need that if I'll be using only one method from there?
So: this works, but I don't like it, are there better ways?
Suppose you want to call some method foo() in a background thread. You have already discovered the most basic way. Here's a somewhat preferable variation on what you did:
new Thread(new Runnable() {
#Override
public void run() {
foo();
}
}).start();
OK, so I wrote six lines of Java code to call one function. Yes, that's kind of verbose. Welcome to Java (or at least, Welcome to Java7. If it can be done more concisely in Java8, I haven't yet learned how.)
This approach has a couple of problems that are worse than verbosity though:
1) You create and destroy a new thread each time you want to call a background method. Creating and destroying threads is relatively expensive.
2) If the background tasks take significant time to perform relative to how often you invoke them, you have no means to control the number of them that are running at the same time. In a busy application, it could keep growing until you get an OutOfMemoryError.
A better approach is to use a thread pool:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
...
final int NUM_THREADS = ...;
final ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
...
executorService.submit(new Runnable() {
#Override
public void run() {
foo();
}
});
Each time you submit a new task to the thread pool, it will wake an already existing thread, and the thread will perform the task and then go back to sleep. No threads are created or destroyed except when the pool starts up.
Also, if all of the threads are busy when you submit the new task, the task will be added to a queue, and it will be performed later when a worker thread becomes available.
This is just a simple example: The java.util.concurrent package gives you many more options including the ability to limit the size of the queue, the ability to make thread pools that grow or shrink depending on demans, and perhaps most important of all, the ability to wait for a task to complete, and a way to get a return value from a completed task.
Check it out. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-frame.html
A synchronized method locks the method's class object so that only one thread can be executing that method at a time. This is useful for situations where you don't want multiple threads to be reading or writing to the same file or stream at the same time, for example.
If you need each thread to read its own separate configuration file, you probably don't need to synchronize the readConfigFile() method. On the other hand, you do need to synchronize it if every thread reads the same config file.
But if all of the threads are reading the same config file, perhaps you should only have one thread (or perhaps the main parent thread) read the file once, and then pass the resulting parsed config values to each thread. This saves a lot of I/O.
I have a requirement to run a thread in background in java and may need to pass some information to the thread before it starts doing its actual function.
How to implement this?
Secondly, is it possible to start a thread which does further operation and exit from request context. Please note that I have to implement in a web application.
An example to answer your first question:
class NewThread extends Thread
{
public String someInformation;
#Override
public void run()
{
System.out.println(someInformation);
}
}
public class YourClass
{
public void startANewThread()
{
NewThread newThread = new NewThread();
newThread.someInformation = "hello";
newThread.start();
}
}
As for your second question: This code should run in a web application, but you must be extremely careful to make sure, that these background Threads will finish at some point, or else that would be a nice little memory leak.
Please note, that if you want to share information when both Threads are running, you need to synchronize information access.
Depending on what the background Thread does it might make sense to use a framework like Quartz
is it possible to start a thread which does further operation and exit from request context. Please note that I have to implement in a web application.
You can use an ExecutorService to pass any number of tasks to and shutdown when you have finished with it.
Try this block of code, with two threads, where one thread will run in background and another thread will start executing the task. And here you can set a return type as well unlike thread.run() method.
FutureTask<Response> future = new FutureTask<>(newCallable<Response>() {
public yourreturntype call() {
doSomething(Thread1);
}
});
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(future);
doSomethingelse(Thread2)
//This thread doesnot wait for thread1 to complete
I'm trying to figure out how to multithread in java. Right now, my program works fine with no concurrency but I want to implement multithreading to help speed it along.
The program runs several objects of a separate sub class and 50% of the time evaluation for each of those objects is spent in a process which only utilizes one core rather than the 8 available. These objects are completely independent of one another until but are used as inputs in the program.
I am trying to multithread this by having the subclass implement Runnable and then have my program use a thread for each such object. Would this be the correct way?
However, how are threads in java handeled? Would I need to dispose of the threads after each run? How does join work?
thanks
Don't manage threads manually, take a look at executors and thread pools in java
You're pretty much on track. You'll create a Thread object
Runnable r = new MyClassImplementingRunnable();
Thread t = new Thread(p);
t.start();
t.join(); // wait for thread to die
The Thread object is garbage collected like any other object, the thread itself dies when the run method completes. The key thing is that your Runnable's run method really must guarantee to return, your design cannot depend on being able to kill thread from the outside.
If you are going to have lots of threads you need to wait for them all to finish, so you can either keep a collection of the threads you've started and then use t.join( smallNumberOfMillis) to see which of them has finished. That's a little inefficient so there are other techniques for allowing threads to communicate with each other, I'd suggest reading this article about them.
#denis also mentions that the Executor and related classes provides a nicer abstraction above Threads. If you have an interest in learning the background then manually managing Threads is interesting. If you just want to get the job done, follow Denis' suggestion.
Take a look at http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
The constructor takes the number of threads you want. In this case the same as your number of cores.
ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(8);
List<Future> futures = new ArrayList<Future>();
foreach(...something...)
futures.add(s.submit(new MyCallable()));
foreach(Future f : futures)
f.get(); // Result of computation
System.out.println("Done");
This is a good way to start multithreading.
public class ThreadExample {
public static void main(String[] args) {
//Main thread
System.out.println("Main thread");
new Thread(new Runnable() {
#Override
public void run() {
//This thread is independent of the main thread
System.out.println("Inner Thread");
}
}).start();
}
}
What are the correct ways/practice/implementation/strategies (or whatever we call it as) for not to wait for code block/method to finish execution in Java?
Assume the following method:
private void myMethod()
{
// Some lines of code here
.....
.....
.....
anotherMethod(); // or this could be a code block
// Again some lines of code here
.....
.....
.....
}
In this case, I expect myMethod() should not wait for code to finish execution of anotherMethod(). I can also assure here that subsequent lines of code do not depend on anything getting executed within anotherMethod().
You can start it in another Thread if there is no dependency .
new Thread(new Runnable(){
public void run(){
anotherMethod();
}
}).start();
Use
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
#Override
public void run() {
anotherMethod();
}
});
// this is called automatically when the object is gc-ed,
// but you should not rely on this, hence the explicit call
executor.shutdown();
To quote Effective Java:
Not only should you refrain from writing your own work queues, but you
should generally refrain from working directly with threads. The key abstraction
is no longer Thread, which served as both the unit of work and the mechanism for
executing it. Now the unit of work and mechanism are separate. The key abstraction is the unit of work, which is called a task. There are two kinds of tasks: Runnable and its close cousin, Callable (which is like Runnable, except that it
returns a value). The general mechanism for executing tasks is the executor ser-
vice. If you think in terms of tasks and let an executor service execute them for
you, you gain great flexibility in terms of selecting appropriate execution policies.
In essence, the Executor Framework does for execution what the Collections
Framework did for aggregation.
Note that you'd better create your executor only once, store it in an instance field and reuse it (and shut it down afterwards)
If you are running in JavaEE 6 or spring, you can annotate your anotherMethod() with #Asynchronous and the container will start a new thread for you.
If you want to invoke the method in the same thread, then the method itself must provide an asynchronous (i.e. non-blocking) implementation. Usually this will involve returning some sort of callback such as a Future, which you can poll/query later to fetch the actual result. An example of this is the ExecutorService.submit() calls - the code you supply will be run, but in a background thread leaving you free to call other methods in the meantime.
I bolded the word invoke before, since fundamentally the only way in Java to have two things happening at once is to use multiple threads. So the method/code block/whatever will have to be executing in a background thread one way or another - usually this is handled for you in an asynchronous method by using some sort of thread pool or whatever is appropriate.
If the method doesn't provide an asynchronous interface, however, the only way to get its logic to run in another thread is to spawn that thread yourself, as org.life.java suggests.