Does Java actually run threads in parallel - java

I would like to understand that does java actually run multiple threads in parallel in a multi core CPU, or there is context switching between threads and only one thread is active and others are waiting for their turn to run.
In other words, is there a possibility that 2 threads are running in parallel???
Because my Thread.currentThread() does not give me a array of threads, but only one thread which is running.
So what is the truth, does only one thread run at a time while others wait or multiple threads can run in parallel, if yes , then why my Thread.currentThread() method return only 1 thread object.
Edit : .....
I have created 2 classes to count numbers
1 class does it synchronously and the other one divides it into two halves and executes the two halves in 2 threads..(intel i5(4 CPUs), 8GB ram)
the code is as follows :
common class :
class Answer{
long ans = 0L;}
Multi Thread execution :
public class Sheet2 {
public static void main(String[] args) {
final Answer ans1 = new Answer();
final Answer ans2 = new Answer();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
for(int i=0;i<=500000; i++) {
ans1.ans = ans1.ans + i;
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
for(int i=500001;i<=1000000; i++) {
ans2.ans = ans2.ans + i;
}
}
});
long l1 = System.currentTimeMillis();
try {
t1.start();t2.start();
t1.join();
t2.join();
long l2 = System.currentTimeMillis();
System.out.println("ans :" + (ans1.ans + ans2.ans) +" in "+(l2-l1) +" milliseconds");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Single Thread execution :
public class Sheet3 {
public static void main(String[] args) {
final Answer ans1 = new Answer();
long l1 = System.currentTimeMillis();
for(int i=0;i<=1000000; i++) {
ans1.ans = ans1.ans + i;
}
long l2 = System.currentTimeMillis();
System.out.println("ans :" + (ans1.ans ) +" in "+(l2-l1) +" milliseconds"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
My Single thread execution is faster than my multi threaded execution, I though the context switching was putting a overhead on the execution initially and hence the multithreaded execution output was slower, now I am having muti core CPU (4 CPU), but still single threaded execution is faster in this example..
Can you please explain the scenario here... is it because my other processes are eating up the other cores and hence my threads are not running in parallel and performing time slicing on the CPU ???
Kindly throw some light on this topic.
Thanks in advance.
Cheers.!!!

In short yes it does run on separate threads. You can test it by creating 100 threads and checking in your process explorer it will say 100 threads. Also you can do some computation in each thread and you will see your multicore processor go upto 100% usage.
Thread.currentThread gives you the current thread you are running from.
When you start your program you are running on the "main" thread.
As soon as you start a new thread
new Thread(myRunnable);
any code located in the myRunnable will run on the new thread while your current thread is is still on the main Thread.
If you check out the API http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html it gives allot more detailed description of the thread.

The actual threading mechanism can vary between CPU architectures. But the real problem is that you're misinterpreting the method name. Thread.currentThread() doesn't return the thread executing at the current moment in time; it returns the thread currently executing the method call, that is, itself.

Yes it does. Run any simple infinite loop on more than one threads and you'll see the cpu usage > 100% on a multi-core CPU.

Yes it does run threads concurrently .That is the very purpose of the multithreading concept .you may find the folowing discussion helpful :
Current Thread Method java

Not a complete answer here, just adding to what others already have said:
The Java Language Specification does not require that threads run in parallel, but it allows them to do so. What actually happens in any given Java Virtual Machine depends on how that JVM is implemented.
Any practical JVM will create one "native" (i.e., operating system) thread for each Java thread, and let the operating system take care of scheduling, locking, waiting, notifying,...

Related

Java : Thread Questions

I'm trying to improve my JAVA. Now i have one questions i don't understand about threading.
My trying code is that,
public class MyThread implements Runnable {
private int end;
private String name;
public MyThread(String name, int end) {
this.end = end;
this.name = name;
}
#Override
public void run() {
for (int i = 0; i < end; i++) {
System.out.println(name + " : " + i);
}
}
}
public class ThreadLesson {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyThread("thread1", 6));
Thread thread2 = new Thread(new MyThread("thread2", 5), "thread2");
thread1.start();
thread2.start();
}
}
On lesson output is
thread1 : 0
thread2 : 0
thread2 : 1
thread2 : 2
thread1 : 1
thread2 : 3
thread1 : 2
thread2 : 4
thread1 : 3
thread1 : 4
thread1 : 5
My outout is
Thread1:0
Thread2:0
Thread1:1
Thread1:2
Thread1:3
Thread1:4
Thread1:5
Thread2:1
Thread2:2
Thread2:3
Thread2:4
My Question is,
Why my out is not same lesson output ? There have some problem or who write that lesson just edit output for article to be beaty.
Somewhere in the lesson this might have been written in bold letters . You should not expect same results as shown here. You have started 2 threads by passing 2 different runnables. WIthout proper synchronization, there is no way of telling what the output would be.
Yes, you might find that very odd at the beginning that the values obtained vary greatly. In fact, there is no way to determine the proper output when two or more unsynchronized thread are allowed to run simultaneously.
This can be understood as
When threads are created they are said to be born state, you do not run a thread by using the run() but you use the start(). Now you may ask the reason behind the logic.
It is quite simple, if you use the run() then the processor must run the thread at that moment, which can cause problem. But if you use the start() then you tell the processor that you want to run the thread. Now after this the processor will take care of the thread as soon as it is free to do so.
It must be clear that the modern processors perform a number of task simultaneously. To achieve this, they can use either Round-Robin method or Preemptive scheduling to complete the task.
In time-slicing, each process is given same amount of processor time. Whereas in preemptive scheduling, the task with higher priority is given the preference.
Now when a number of threads run simultaneously then it depends on the operating system to allocate the processor to any thread. So any thread can get the processor which can change the output you see.
Now if the threads are synchronized then the conditions change and the program can have a fixed path.
We can not predict output pattern in this kind of cases as output will be solely depend upon jvm's Thread manager. If you want to have a predicted output you can go for Thread.sleep(timeinml) method as this will provide thread synchronization

Order of execution and Thread.sleep

Recently I've seen some code which depends on order of execution in different threads which was achieved by calling Thread.sleep with some values. It worked without any problems but I'm sure that in some rare cases it would not. I wrote some code where order of output depends on how precisely Thread.sleep works.
public class Test {
public static Thread createDelayedPrintThread(final String text,
final long delay) {
return new Thread() {
public void run() {
try {
Thread.sleep(delay);
System.out.print(text);
} catch (InterruptedException e) {
}
}
};
}
public static void main(String[] args) {
Thread t1 = createDelayedPrintThread("t1", 10);
Thread t2 = createDelayedPrintThread("t2", 10);
t1.start();
t2.start();
}
}
This code obliviously can output booth t1t2 and t2t1 so I made delays different:
Thread t1 = createDelayedPrintThread("t1", 10);
Thread t2 = createDelayedPrintThread("t2", 20);
Now it outputs t1t2 but I still sometimes get t2t1. It usually happens when I do some CPU/IO intensive operations.
If I change delays to extremely big values
Thread t1 = createDelayedPrintThread("t1", 1_000); // one second
Thread t2 = createDelayedPrintThread("t2", 60_000); // one minute
would be there any guarantees that the application will output t1t2?
First, your understanding is correct; no amount of Thread.sleep() (and by the way, since Java 5 you should really be using TimeUnit instead, as in TimeUnit.SECONDS.sleep(2L)) will guarantee in-order execution; you cannot guarantee when the OS will schedule this or that thread.
would be there any guarantees that the application will output t1t2?
Yes.
For instance, a volatile boolean variable shared by those two threads will do (although you'll need to busy wait so this is not ideal). Another example is a Semaphore.
Solutions are many, and what you will end up with depends entirely upon your requirements.
Thread.sleep is not guarantees.
Java tutorial, about Thread.sleep():
"However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified."
So, you need add other multithreading logic for guarantees execution order.

Why are the threads executed in this order?

Practicing multi thread java examples ,here i am creating thread A in class A and thread B in class B .Now starting those two threads by creating objects .here i am placing the code
package com.sri.thread;
class A extends Thread
{
public void run()
{
System.out.println("Thread A");
for(int i=1;i<=5;i++)
{
System.out.println("From thread A i = " + i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
System.out.println("Thread B");
for(int i=1;i<=5;i++)
{
System.out.println("From thread B i = " + i);
}
System.out.println("Exit from B");
}
}
public class Thread_Class
{
public static void main(String[] args)
{
new A().start(); //creating A class thread object and calling run method
new B().start(); //creating B class thread object and calling run method
System.out.println("End of main thread");
}
//- See more at: http://www.java2all.com/1/1/17/95/Technology/CORE-JAVA/Multithreading/Creating-Thread#sthash.mKjq1tCb.dpuf
}
i didn't understand the flow of execution ,tried by debugging but didn't get it.how the flow of execution is .Here i am placing the out put which confusing me.
Thread A
Thread B
End of main thread
From thread B i = 1
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5
Exit from B
From thread A i = 1
From thread A i = 2
From thread A i = 3
From thread A i = 4
From thread A i = 5
Exit from A
Why does the loop in thread B finish before the loop in thread A is entered?
Unless you have multiple processors, the threads are sharing a processor on a time slice basis. The total time to execute one of your threads may be less than the time slice, so whichever thread gets dispatched first will complete before the other runs at all.
Try adding a short Thread.sleep call in the run methods.
There really is no guaranteed order of execution when executing multiple threads. The threads are independent of each other.
The link in the source code explains it:
Here you can see that both outputs are different though our program
code is same. It happens in thread program because they are running
concurrently on their own. Threads are running independently of one
another and each executes whenever it has a chance.
The threads are executing at the same time. One isn't executing inside the other. Each thread gets CPU time, does some work, and then waits while the CPUs are busy with other things. It could run differently each time depending on what else is happening on the computer.
If you expected the threads' output messages to be interlaced, they will be, to an extent, if you increase your loops to several thousands of iterations. Right now the code finishes so quickly it's hard to see that they really are running in parallel.

How to Obtain Thread Info/Statistics in Java

Title says it all. I have some code which is included below and I am wondering how I would go about obtaining the statistics/information related to the threads (i.e. how many different threads are running, names of the different threads). For consistency sake, image the code is run using 22 33 44 55 as command line arguments.
I am also wondering what the purpose of the try blocks are in this particular example. I understand what try blocks do in general, but specifically what do the try blocks do for the threads.
public class SimpleThreads {
//Display a message, preceded by the name of the current thread
static void threadMessage(String message) {
long threadName = Thread.currentThread().getId();
System.out.format("id is %d: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
String info[];
MessageLoop(String x[]) {
info = x;
}
public void run() {
try {
for (int i = 1; i < info.length; i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
threadMessage(info[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
}
public static void main(String args[])throws InterruptedException {
//Delay, in milliseconds before we interrupt MessageLoop
//thread (default one minute).
long extent = 1000 * 60;//one minute
String[] nargs = {"33","ONE", "TWO"};
if (args.length != 0) nargs = args;
else System.out.println("assumed: java SimpleThreads 33 ONE TWO");
try {
extent = Long.parseLong(nargs[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("First Argument must be an integer.");
System.exit(1);
}
threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop(nargs));
t.start();
threadMessage("Waiting for MessageLoop thread to finish");
//loop until MessageLoop thread exits
int seconds = 0;
while (t.isAlive()) {
threadMessage("Seconds: " + seconds++);
//Wait maximum of 1 second for MessageLoop thread to
//finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > extent) &&
t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
//Shouldn't be long now -- wait indefinitely
t.join();
}
}
threadMessage("All done!");
}
}
you can use VisualVM for threads monitoring. which is included in JDK 6 update 7 and later. You can find visualVm in JDK path/bin folder.
VisualVM presents data for local and remote applications in a tab
specific for that application. Application tabs are displayed in the
main window to the right of the Applications window. You can have
multiple application tabs open at one time. Each application tab
contains sub-tabs that display different types of information about
the application.VisualVM displays real-time, high-level data on
thread activity in the Threads tab.
For the first issue:
Consider using VisualVM to monitor those threads. Or just use your IDEs debugger(eclipse has such a function imo).
I am also wondering what the purpose of the try blocks are in this particular example.
InterruptedExceptions occur if Thread.interrupt() is called, while a thread was sleeping. Then the Thread.sleep() is interrupted and the Thread will jump into the catch-code.
In your example your thread sleeps for 4 seconds. If another thread invokes Thread.interrupt() on your sleeping one, it will then execute threadMessage("I wasn't done!");.
Well.. as you might have understood now, the catch-blocks handle the sleep()-method, not a exception thrown by a thread. It throws a checked exception which you are forced to catch.
If you are not able to use tools like VisualVM (which is very useful, IMHO), you can also dump the thread stack in Java, e.g. to your logfile. I am using such dumps on my server programs, when certain thresholds are crossed. I found doing such snapshots as part of the program very helpful. Gives you some hints on what happened before the system crashes and it is too late to use profilers (deadlock, OutOfMemory, slowdown etc.). Have a look here for the code: Trigger complete stack dump programmatically?

How to check the number of currently running threads in Java?

I'm looking for a way to see the number of currently running threads
Through Windows first
Programmatically
This will give you the total number of threads in your VM :
int nbThreads = Thread.getAllStackTraces().keySet().size();
Now, if you want all threads currently executing, you can do that :
int nbRunning = 0;
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getState()==Thread.State.RUNNABLE) nbRunning++;
}
The possible states are enumerated here: Thread.State javadoc
If you want to see running threads not programmaticaly but with a Windows tool, you could use Process Explorer.
You can get all the threads and their stack traces running in the JVM uses Thread.getAllStackTraces()
In response to your following comment
In the following piece of code: while(resultSet.next()) {
name=resultSet.getString("hName"); MyRunnable worker = new
MyRunnable(hName); threadExecutor.execute( worker ); } . My thread
pool has size of 10. I need to make sure that my program working
correctly with multi-threadings & want to check how many threads are
running at a certain moment. How can I do this?
to another answer, I suggest that you profile your code with JVisualVM and check if your thread pool is working as it should. The reason behind this suggestion is that then you don't have to bother with all the other housekeeping threads that JVM manages. Besides what you want to do is why tools like JVisualVM are made for.
If you are new to profiling Java programs, JVisualVM lets you see what goes on under the hood while you are running your code. You can see the Heap, GC activity, inspect the threads running/waiting any sample/profile your cpu or memory usage. There are quite a few plugins as well.
From Windows:
There's bound to be a performance counter for the process that can tell you that.
Programmatically:
There's Thread#activeCount:
Returns an estimate of the number of active threads in the current thread's thread group and its subgroups. Recursively iterates over all subgroups in the current thread's thread group.
Or more directly, ThreadGroup#activeCount:
Returns an estimate of the number of active threads in this thread group and its subgroups.
and ThreadGroup#getParent:
Returns the parent of this thread group.
First, if the parent is not null, the checkAccess method of the parent thread group is called with no arguments; this may result in a security exception.
All of which seem to suggest something along the lines of:
int activeThreadTotalEstimate() {
ThreadGroup group;
ThreadGroup parent;
group = Thread.currentThread().getThreadGroup();
while ((parent = group.getParent()) != null) {
group = parent;
}
return group.activeCount();
}
Code snippet:
import java.util.Set;
import java.lang.Thread.State;
public class ActiveThreads {
public static void main(String args[]) throws Exception{
for ( int i=0; i< 5; i++){
Thread t = new Thread(new MyThread());
t.setName("MyThread:"+i);
t.start();
}
int threadCount = 0;
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for ( Thread t : threadSet){
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup() &&
t.getState() == Thread.State.RUNNABLE){
System.out.println("Thread :"+t+":"+"state:"+t.getState());
++threadCount;
}
}
System.out.println("Thread count started by Main thread:"+threadCount);
}
}
class MyThread implements Runnable{
public void run(){
try{
Thread.sleep(2000);
}catch(Exception err){
err.printStackTrace();
}
}
}
output:
Thread :Thread[main,5,main]:state:RUNNABLE
Thread count started by Main thread:1
Explanation:
Thread.getAllStackTraces().keySet() provides you list of all Threads, which have been started by both Program and System. In absence of ThreadeGroup condition, you will get System thread count if they are active.
Reference Handler, Signal Dispatcher,Attach Listener and Finalizer

Categories