What happens if a thread has been executed same time more than once. Lets say I have thread like
private Runnable mySampleThread() {
return new Runnable() {
#Override
public void run() {
//something is going on here.
}
};
}
And I created an ExecutorService with fixed thread pool of 10. What happens if I execute mySampleThread 10 times in this ExecutorService.
Something like below,
ExecutorService mySampleExecutor = Executors.newFixedThreadPool(10);
while (i <= 10) {
mySampleExecutor.execute(mySampleThread);
i++;
}
Answer is very simple. Executor will execute Runnable object (it's not the Thread object) as described in documentation Interface Executor
Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.
Basically, Executor will pick up one thread of it's internal pool (ThreadPoolExecutor), assign runnable to it a execute run() method.
Firstly elaborate your problem or query.
Nevertheless, assuming that you are calling the method "mySampleThread()" without missing brackets. This method actually returns a new Runnable object every time, so you are passing a new runnable all 10 times to executor. And it means you are submitting 10 different tasks to executor. So if executor creates different thread for every task (that depends upon its implementation), then whatever you code inside run() will be executed 10 times in 10 different threads.
And as described in other answers, the runnable object being passed to executor is not a thread.
Hope it clarifies.
By the way, you may try running the program.
As other answers clearly state, there will be as many new threads as the number of calls (might be less due to used executor, I'm focusing on Runnable reusage, limiting number of threads with executor is well explained in other answers). All of them created with single Runnable object.
What's worth mentioning, and I personally made use of this quite a few times - this is one of the ways to share data between multiple threads as all of these threads share Runnable that was used for creation. Synchronization issues come into play at this point, but that's another story.
Here's code to show the typical usage and the aforementioned synchronization problem.
import java.util.concurrent.ExecutorService;
class MyThread implements Runnable {
public int counter = 0;
#Override
public void run() {
for (int i = 0; i < 10000; i++) {
counter++;
}
}
}
class MySynchronizedThread implements Runnable {
public int counter = 0;
#Override
public void run() {
for (int i = 0; i < 10000; i++) {
synchronized (this) {
counter++;
}
}
}
}
public class RunnableTest {
public static void main(String[] args) throws InterruptedException {
MyThread runnableObject = new MyThread();
ExecutorService ex = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
ex.execute(runnableObject);
}
ex.shutdown();
ex.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
System.out
.println("Without synchronization: " + runnableObject.counter);
MyThread runnableSynchronizedObject = new MyThread();
ExecutorService ex2 = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
ex2.execute(runnableSynchronizedObject);
}
ex2.shutdown();
ex2.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
System.out.println("Without synchronization: "
+ runnableSynchronizedObject.counter);
}
}
There will be no differences in mySampleExecutor.execute(mySampleThread);, mySampleThread method return a new Runnable object. every thread will have it's own Frames
Related
This code I have is not executing tasks in parallel,
it only executes the code in this case once (whatever is in the for loop, but it should be 2) :
public class mqDirect {
public static void main(String args[]) throws Exception {
int parallelism = 2;
ExecutorService executorService =
Executors.newFixedThreadPool(parallelism);
Semaphore semaphore = new Semaphore(parallelism);
for (int i = 0; i < 1; i++) {
try {
semaphore.acquire();
// snip ... do stuff..
semaphore.release();
} catch (Throwable throwable) {
semaphore.release();
}
executorService.shutdownNow();
}
}
}
In Java the main way to make code work in parallel is to create a Thread with a new Runnable as a constructor parameter. You then need to start it.
There are many tutorials to help you get this to happen properly.
As your code stands you are merely creating an ExecutorService (and not using it), creating a Semaphore (which should be done in the thread but isn't), performing some process and then shutting down the Executor.
BTW: ShutDownNow is probably not what you want, you should just use ShutDown.
OK, So I found this good tutorial
http://programmingexamples.wikidot.com/threadpoolexecutor
And I have done something like
public class mqDirect {
int poolSize = 2;
int maxPoolSize = 2;
long keepAliveTime = 10;
ThreadPoolExecutor threadPool = null;
final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
5);
public mqDirect()
{
threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize,
keepAliveTime, TimeUnit.SECONDS, queue);
}
public void runTask(Runnable task)
{
threadPool.execute(task);
System.out.println("Task count.." + queue.size());
}
public void shutDown()
{
threadPool.shutdown();
}
public static void main (String args[]) throws Exception
{
mqDirect mtpe = new mqDirect();
// start first one
mtpe.runTask(new Runnable()
{
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
System.out.println("First Task");
runMqTests();
Thread.sleep(1000);
} catch (InterruptedException ie)
{
}
}
}
});
// start second one
/*
* try{ Thread.sleep(500); }catch(InterruptedException
* ie){}
*/
mtpe.runTask(new Runnable()
{
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
System.out.println("Second Task");
runMqTests();
Thread.sleep(1000);
} catch (InterruptedException ie)
{
}
}
}
});
mtpe.shutDown();
// runMqTests();
}
And it works !
But the problem is , this duplicated code ... runMqtests() is the same task, is there a way to specify it to run in parallel without duplicating the code?
The example I based this off is assuming each task is different.
This code I have is not executing tasks in parallel, it only executes the code in this case once (whatever is in the for loop, but it should be 2) :
Just because you instantiate an ExecutorService instance doesn't mean that things magically run in parallel. You actually need to use that object aside from just shutting it down.
If you want the stuff in the loop to run in the threads in the service then you need to do something like:
int parallelism = 2;
ExecutorService executorService = Executors.newFixedThreadPool(parallelism);
for (int i = 0; i < parallelism; i++) {
executorService.submit(() -> {
// the code you want to be run by the threads in the exector-service
// ...
});
}
// once you have submitted all of the jobs, you can shut it down
executorService.shutdown();
// you might want to call executorService.awaitTermination(...) here
It is important to note that this will run your code in the service but there are no guarantees that it will be run "in parallel". This depends on your number of processors and the race conditions inherent with threads. For example, the first task might start up, run, and finish its code before the 2nd one starts. That's the nature of threaded programs which are by design asynchronous.
If, however, you have at least 2 cores, and the code that you submit to be run by the executor-service takes a long time to run then most likely they will be running at the same time at some point.
Lastly, as #OldCurmudgeon points out, you should call shutdown() on the service which allows current jobs already submitted to the service to run as opposed to shutdownNow() which cancels and queued jobs and also calls thread.interrupt() on any running jobs.
Hope this helps.
I was trying to understand the monitor on Java and the question that came to me is how to make the threads that run the same synchronized method to wait?
I was trying to make a simple program that would make 3 threads to use the same method to add to N element 1 for total of 10 000 times and I was wondering how to make other threads to wait when one is doing adding method and notifyAll after it is done if I would start all of them at the same time.
Here is my program that I wrote without wait/notify functions :
class Swapper implements Runnable{
int number;
Swapper(int number){
this.number=number;
}
#Override
public void run() {
while (mainClass.counter>0){
mainClass.incArrayElement(number);
}
}
}
public class mainClass {
public static volatile int counter = 10000;
public static volatile int[] testArray = new int[]{0,0,0};
public static synchronized void incArrayElement(int index){
if (counter>0) {
testArray[index - 1]++;
counter--;
}
else {
return;
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new Swapper(1));
Thread thread2 = new Thread(new Swapper(2));
Thread thread3 = new Thread(new Swapper(3));
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
int checkSum = 0;
for (int i = 0; i < testArray.length; i++) {
System.out.println(testArray[i]);
checkSum+=testArray[i];
}
System.out.println(checkSum);
}
}
When a thread calls the synchronized method 'incArrayElement' of your class it acquires the lock of that object, any new thread cannot call ANY synchronized method of the same object as long as previous thread which had acquired the lock does not release the lock. Hence all other threads will be blocked until the execution is complete.
So why do you need to have the threads to call wait() as they are blocked already and waiting.
Unfortunately your example is not well chosen.
The method declared synchronized is controlled in a way that other threads cannot call it unless it has finished execution. Then one of the threads calls this method again. 'Which thread' cannot really be told because you have no control over it. Using wait and notify functions will not give you control over this neither. So if that is what you are looking for, you cannot achieve what you want. It will remain indeterministic for you.
If simply assuring that the method is called by only one thread at a time, then you already have that behavior, no need for wait or notify.
I'm pretty new using Threads and I just did a little program to understand how it works. As a example a did a prime numbers exercise, the program is running perfectly but what I have discovered is that if I don't use sleep(), the order of the numbers change everytime I press run (without changing the code). So why is happening that?
class Prime extends ThreadDemo implements Runnable
{
public void run()
{
for(int i=2;i<=20;i++)
{
if(prime(i))
{
System.out.printf ("Prime No.= %d \n",i);
}
}
}
}
class notPrime extends ThreadDemo implements Runnable
{
int number= 0;
public void run()
{
prime(number);
}
}
class ThreadDemo
{
public boolean prime(int start_value)
{
for(int i=2; i<start_value; i++)
{
if(start_value%i == 0)
{
System.err.printf ("No. Prime = %d \n", start_value);
return false;
}
}
return true;
}
public static void main(String args[])
{
Prime th1 = new Prime();
Thread childOne = new Thread(th1);
childOne.start();
notPrime th2 = new notPrime();
Thread childTwo = new Thread(th2);
childTwo.start();
}
}
This is the result after I pressed run:
This is the result after pressing again run:
The reason this is happening is that threads run in parallel. When you create a bunch of threads, these threads all start doing things at the same time, and it's a race to see which ones finish first. This isn't deterministic, and sometimes the threads will finish in a different order.
The reason sleep could change this is that sleep will give the threads you created first a head start.
There are two reasons why this happens :
Your prime method is not synchronized.
Even if you synchronize the prime method, you are passing different instances of ThreadDemo to your threads. Locks are obtained on objects. If two threads are passed two different objects of ThreadDemo, each thread will lock its own instance of ThreadDemo thus allowing the Threads to run in parallel.
There are a couple of changes you need to make to your code to make sure that the same ThreadDemo is used for both your threads.
class NotPrimeRunnable implements Runnable {
private ThreadDemo threadDemo;
int number = 0;
public NotPrimeRunnable(ThreadDemo threadDemo) {
this.threadDemo = threadDemo;
}
public void run() {
threadDemo.prime(number);
}
}
class PrimeRunnable implements Runnable {
private ThreadDemo threadDemo;
public PrimeRunnable(ThreadDemo threadDemo) {
this.threadDemo = threadDemo;
}
#Override
public void run() {
for (int i = 2; i <= 20; i++) {
if (threadDemo.prime(i)) {
System.out.printf("Prime No.= %d \n", i);
}
}
}
}
class ThreadDemo {
public synchronized boolean prime(int start_value) {
for (int i = 2; i < start_value; i++) {
if (start_value % i == 0) {
System.err.printf("No. Prime = %d \n", start_value);
return false;
}
}
return true;
}
public static void main(String args[]) {
ThreadDemo runnableTask = new ThreadDemo();
PrimeRunnable th1 = new PrimeRunnable(runnableTask);
Thread childOne = new Thread(th1);
childOne.start();
NotPrimeRunnable th2 = new NotPrimeRunnable(runnableTask);
Thread childTwo = new Thread(th2);
childTwo.start();
}
}
This will fix your problem.
Wikipedia defines thread as: "In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler".
Schedulers are software modules that run in the SO Kernel and manages the processes and threads execution. Schedulers use time-division multiplexing (as in multitasking) algorithms to ensure that all threads and process will be able to execute. One of the scheduler`s characteristics in SOs such as Windows, Mac OS and Linux is that the CPU switches between different software threads. As stated in Wikipedia: "This context switching generally happens frequently enough that the user perceives the threads or tasks as running at the same time."
Based on these considerations, we can explain your software behavior. Non-real time Operating System such as windows and MAC OSx, and many Linux distributions use scheduler algorithms that are non deterministic, so we cant predict the execution order of the threads, then it`s likely every time you execute you are going to get a different result regarding your text output order.
When you use sleep between the threads execution, it seems that the time amount chosen is enough to th1 execute completely before th2 starts. So the output is shown in the correct order.
I'm trying to write a class that can only run X(Let's say 3)threads at one time. I have 8 threads that need to execute but I only want to allow 3 to run at once, then wait. Once one of the currently running threads stops, then it will start another. I'm not quite sure how to do this. My code looks like this:
public class Main {
public void start() {
for(int i=0; i<=ALLTHREADS; i++) {
MyThreadClass thread = new MyThreadClass(someParam, someParam);
thread.run();
// Continue until we have 3 running threads, wait until a new spot opens up. This is what I'm having problems with
}
}
}
public class MyThreadClass implements Runnable {
public MyThreadClass(int param1, int param2) {
// Some logic unimportant to this post
}
public void run() {
// Generic code here, the point of this is to download a large file
}
}
As you can see above most of it is stubbed out pseudo-code. I can post it if anyone would like but it's unimportant to the main question.
you should use thread pooling mechanism here to run multiple threads.
to make it easy we can go for thread pool executor in java which is very easy
create a fixed pool of 3 threads using executors method.
write a for loop for 8 iteration and call execute on each thread and it will run only 3 threads at a time.
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 8; i++) {
Task task = new Task(someParam, someParam);
executor.execute(task);
}
executor.shutdown();
Unless this is homework, you can use Executors.newFixedThreadPool(3) which returns an ExecutorService with a max of 3 threads to perform Runnable tasks.
Does using a synchronized block inside the run method makes any sense? I thought it does, as long as I'm using a relevant lock, not the instance of Runnable containing this run method. Reading the answers to similar questions on stackoverflow seemed to confirm this. I tried to write some simple code to test it and the synchronized block inside the run method doesn't prevent from data corruption:
public class Test {
public Test() {
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 1000; i++) {
es.execute(new Runnable() {
#Override
public void run() {
synchronized (lock) {
sum += 1;
}
}
});
}
es.shutdown();
while(!es.isTerminated()) {
}
}
private int sum = 0;
private final Object lock = new Object();
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.sum);
}
}
Why this code generates incorrect results? Is this because the synchronized block or some other mistake? I feel like I'm missing something basic here.
It's possible your executor encounters some sort of unexpected error. If that happens you won't know it because you are not getting any return value to check.
Try switching to submit() instead of execute() and store a list of Future instances the Executor gives you. If the final sum is less than 1000, iterate the futures and get() each one. If an exception is raised you'll see what happened with that particular runnable task.
Apart from your simple example, which looks OK, you should be careful with synchronization in Runnables to prevent them from blocking each other when one Runnable waits for some resource to be released only by another Runnable later in the queue that has not started yet and never will since the current waiting Runnable must finish first.
With enough worker Threads executing the jobs this is less likely to occur, though.