How is default new thread name given in java? - java

When I run this program
public class Fabric extends Thread {
public static void main(String[] args) {
Thread t1 = new Thread(new Fabric());
Thread t2 = new Thread(new Fabric());
Thread t3 = new Thread(new Fabric());
t1.start();
t2.start();
t3.start();
}
public void run() {
for(int i = 0; i < 2; i++)
System.out.print(Thread.currentThread().getName() + " ");
}
}
I get output
Thread-1 Thread-5 Thread-5 Thread-3 Thread-1 Thread-3
Is there any specific reason why the threads are given names with odd numbers - 1, 3, 5... Or is it unpredictable?

new Thread(new Fabric());
Since Fabric is a Thread, you created 2 threads here :)
JDK8 code:
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}

The default numeric value in the Thread name is an incremented value unless the name is specified when creating the Thread. Fabric extends Thread, and you are passing the Fabric instance to create another Thread - thus the internal Thread counter is incremented twice as 2 threads are created during the process.

If you change the program like given below you will get the thread numbering in sequence.
public class Fabric extends Thread {
public static void main(String[] args) {
Thread t1 = new Fabric();
Thread t2 = new Fabric();
Thread t3 = new Fabric();
t1.start();
t2.start();
t3.start();
}
public void run() {
for(int i = 0; i < 2; i++)
System.out.print(Thread.currentThread().getName() + " ");
}
}
and the output is
Thread-0 Thread-2 Thread-2 Thread-1 Thread-0 Thread-1

As others have pointed out, it's just an incrementing counter.
The reason why your log file does not print your thread names in order, is because java does not guarentee the order of execution of the started threads.
If you want to force the order, then you have to make the threads wait for eachother. A possible way to do this, is using a CountDownLatch.
private static CountDownLatch latch;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Fabric());
Thread t2 = new Thread(new Fabric());
Thread t3 = new Thread(new Fabric());
// the countdown starts at 1.
latch = new CountDownLatch(1);
t1.start();
// the thread will wait till the countdown reaches 0.
latch.await();
latch = new CountDownLatch(1);
t2.start();
latch.await();
latch = new CountDownLatch(1);
t3.start();
latch.await();
}
public void run() {
for(int i = 0; i < 2; i++)
System.out.print(Thread.currentThread().getName());
// thread is done: set counter to 0.
latch.countDown();
}
On the other hand, some classes use a ThreadFactory to assign thread names. (e.g. a ScheduledThreadPoolExecutor). For example the DefaultThreadFactory creates its thread names as follows:
String namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
String threadName = namePrefix + threadNumber.getAndIncrement()

Related

unexpected multi thread output in java

public class ConTest {
#Test
void name2() {
final MyCounter myCounter = new MyCounter();
final Thread t1 = new Thread(() ->
myCounter.increment()
);
final Thread t2 = new Thread(() ->
myCounter.increment()
);
t1.start();
t2.start();
System.out.println(myCounter.count);
}
#Test
void name3() {
final MyCounter myCounter = new MyCounter();
final ExecutorService service = Executors.newFixedThreadPool(2);
for (int i = 0; i < 2; i++) {
service.execute(() -> {
myCounter.increment();
});
}
System.out.println(myCounter.count);
}
static class MyCounter {
private AtomicLong count = new AtomicLong();
public void increment() {
count.incrementAndGet();
}
}
}
AtomicLong is safe when multi thread.
That is, in the example above, it was executed with 2 threads, so the result should be 2 no matter how many times it is executed.
However, after trying both tests several times, the result is sometimes 1. Why is this happening?
You aren't waiting for any of the background threads or tasks to end before you print the value of the counter. To wait on the tasks to exit, you'll need to add this for threads:
t1.join();
t2.join();
Add this for the service, which prevents new tasks being added and waits a sensible period for them to end:
service.shutdown();
boolean done = awaitTermination(pickSuitablyLongPeriod, TimeUnit.MILLISECONDS);
Once you have ensured the background tasks are completed, the correct result should be printed when you run:
System.out.println(myCounter.count);
This is because the threads are still processing when you call the System.out.println. In this case you would need to block the main thread before you print out the counter.
in the example of the Executor you can just await the termination:
final ExecutorService service = Executors.newFixedThreadPool(2);
final MyCounter myCounter = new MyCounter();
for (int i = 0; i < 100; i++) {
service.submit(myCounter::increment);
}
service.shutdown();
while (!service.awaitTermination(100, TimeUnit.MILLISECONDS)) {
System.out.println("waiting");
}
System.out.println(myCounter.count);
you should avoid to block in productive code, have a look at the Publish/Subscribe design pattern
dont forget to use shutdown() with Executors
see the comments here :
// Here you start the 2 threads
for (int i = 0; i < 2; i++) {
service.execute(() -> {
myCounter.increment();
});
}
// we are not sure here that your 2 threads terminate their tasks or not !!
// the print will be executed by the Main Thread and maybe before the 2 threads terminate their
// job ,
// maybe just one terminate , maybe no one from your 2 threads increment the count .
System.out.println(myCounter.count);
You can use Future class , instead of execute you can use submit() , the retrun type will be of Type Futre<?> (accept void ) , after that with the Future object returned the method get() will block the execution until the result returned from the service :
Example method name3() : will return always 2
void name3() {
final MyCounter myCounter = new MyCounter();
final ExecutorService service = Executors.newFixedThreadPool(2);
Future<?> f = null;
for (int i = 0; i < 2; i++) {
f =service.submit(() -> {
myCounter.increment();
});
try {
f.get();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(myCounter.count);
service.shutdown();
}
In addition to the above answers, you could add some prints to better understand what is happening.
In summary. You need to wait for the threads to finish executing before expecting the results, so it is not an issue of AtomicLong.
I modified the code, added some prints, and here are results from an execution.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;
public class ConTest {
#Test
void name2() {
final MyCounter myCounter = new MyCounter();
final Thread t1 = new Thread(() -> {
myCounter.increment();
System.out.println("Counter increment t1 completed and the value is " + myCounter.getCount());
});
final Thread t2 = new Thread(() -> {
myCounter.increment();
System.out.println("Counter increment t2 completed and the value is " + myCounter.getCount());
});
t1.start();
t2.start();
System.out.println(myCounter.count.get());
}
#Test
void name3() {
final MyCounter myCounter = new MyCounter();
final ExecutorService service = Executors.newFixedThreadPool(2);
for (int i = 0; i < 2; i++) {
service.execute(() -> {
myCounter.increment();
System.out.println("incrementing for count and the value is " + myCounter.getCount());
});
}
System.out.println(myCounter.count.get());
}
class MyCounter {
private AtomicLong count = new AtomicLong();
public void increment() {
count.incrementAndGet();
}
public long getCount(){
return count.get();
}
}
}
Results (name2)
1
Counter increment t1 completed and the value is 1
Counter increment t2 completed and the value is 2
Results (name3)
incrementing for count and the value is 1
1
incrementing for count and the value is 2
You could also use a debugger to have a better understanding.

When AtomicInteger is faster than synchronized

I've already read a great number of articles where is said that AtomicInteger class works faster than a synchronize construction. I did some tests on AtomicInteger and "synchronized" and in my tests, it occurs that synchronized is much faster than AtomicInteger. I would like to understand what is going wrong: my test class is incorrect or AtomicInteger works faster in other situations?
Here is my test class:
public class Main {
public static void main(String[] args) throws InterruptedException
{
// creating tester "synchronized" class
TesterSynchronized testSyn = new TesterSynchronized();
// Creating 3 threads
Thread thread1 = new Thread(testSyn);
Thread thread2 = new Thread(testSyn);
Thread thread3 = new Thread(testSyn);
// start time
long beforeSyn = System.currentTimeMillis();
// start
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
long afterSyn = System.currentTimeMillis();
long delta = afterSyn - beforeSyn;
System.out.println("Test synchronized: " + delta + " ms");
// _______________________________________________________
// creating tester "atomicInteger" class
TesterAtomicInteger testAtomic = new TesterAtomicInteger();
thread1 = new Thread(testAtomic);
thread2 = new Thread(testAtomic);
thread3 = new Thread(testAtomic);
// start time
long beforeAtomic = System.currentTimeMillis();
// start
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
long afterAtomic = System.currentTimeMillis();
long deltaAtomic = afterAtomic - beforeAtomic;
System.out.println("Test atomic integer: " + deltaAtomic + " ms");
}
}
// Synchronized tester
class TesterSynchronized implements Runnable {
public int integerValue = 0;
public synchronized void run() {
for (int i = 0; i < 1_000_000; i++)
integerValue++;
}
}
// AtomicInteger class tester
class TesterAtomicInteger implements Runnable {
AtomicInteger atomicInteger = new AtomicInteger(0);
public void run() {
for (int i = 0; i < 1_000_000; i++)
atomicInteger.incrementAndGet();
}
}
Test parameters: 3 threads and 1_000_000 increments;
Result:
Test synchronized: 7 ms. Test atomic integer: 51 ms
I would be glad to understand why this is happening.
UPD
The test will be correct if change the synchronized method to a synchronized block.
// Synchronized tester
class TesterSynchronized implements Runnable {
public int integerValue = 0;
public void run() {
for (int i = 0; i < 1_000_000; i++) {
synchronized (this) {
integerValue++;
}
}
}
}
The obvious difference in your code is that the AtomicIntger version allows interleaving of threads with ever access, whereas the synchronized version does the entire loop each thread in turn.
There may be other issues. For instance, the JVM may merge multiple invocations of a synchronized block. Depending on the platform, incrementAndGet may not be an atomic operation but implemented as a CAS-loop - if contention is high that could be a problem (I am not entirely sure on that).
Whichever way it is arranged, if you have multiple threads concurrently modifying the same memory location it will not be fast.

Why is the program execution isn't as expected [duplicate]

This question already has answers here:
Java. The order of threads execution
(2 answers)
Closed 3 years ago.
Thread two is running first on output though I've called start() method of thread1 at first. Why this is happening?
Output:
Thread two running: 0
Thread two running: 1
Thread one running: 0
Thread two running: 2
....
package interfacetest;
class thread1 extends Thread {
public void run() {
for(int i=0; i<10; i++) {
System.out.println("Thread one running: " +i);
}
}
}
class thread2 extends Thread {
public void run() {
for(int j=0; j<10; j ++) {
System.out.println("Thread two running: " +j);
}
}
}
class InterfaceTest {
public static void main(String[] args) {
thread1 t1 = new thread1();
thread2 t2= new thread2();
t1.start();
t2.start();
}
}
When we start thread, java starts execution of run method in separate thread. And thread ordering is never gauranteed. Here as you are simply starting 2 different threads no gaurantee that they will be executed in sequence.

Usage of countDown latch in java

Am new to java programming and first time using countDown in java,
My code snippet is,
CountDownLatch latch=new CountDownLatch(rows*columns); //rows -2 , columns -3
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
GUIView view = getView(1, 1);
if(view == null) {
if(ViewColumn(j +1) != null){
latch.countDown(); //EDT
continue;
}
latch.countDown(); //EDT
break;
}
new Thread(new countDownThread(view,latch)).start(); //Where i do some other processing and do countDown
}
}
try {
logger.log("Before countdown await");
latch.await();
logger.log("After countdown await");
}
.........
........
As i read from another post,
One of the disadvantages/advantages of CountDownLatch is that its not
reusable once count reaches to zero you can not use CountDownLatch any
more.
My doubt here is am using the same instance latch , inside the for loop. if CountDownLatch is not reusable what will happen if the first iteration latch.countDown() starts and it became zero by third iteration(The latch.countDown() at third iteration is not valid??).
The problem is :
When i debug the for loop(using eclipse), and when control reaches latch.await(); it just hangs. However, if i just run the application no hang happens.
I don't quite understand usage of countDown latch. Please explain me on the same.
Seems here you don't use multithreading, and all work done in one thread, because of you needn't to use CountDownLatch.
Also latch.await(); hang because it waiting for all count of tasks will be done(seems here it //rows -2 , columns -3 = 6) and call latch.countDown();. Read more about in docs.
Here is simple example of use, where t2 wait for t1:
import java.util.concurrent.CountDownLatch;
public class Test {
public static void main(String... s){
final CountDownLatch cdl = new CountDownLatch(1);
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
int i = 5;
while(i-- > 0)
System.out.println("t2 wait me");
cdl.countDown();
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("done");
}
});
t2.start();
t1.start();
}
}
When you initialize CountDownLatch with some value for example:
CountDownLatch latch = new CountDownLatch(3);
It basically means that when method:
latch.countDown();
will be fired three times, the class which will use latch will be released from the await method call.
Of course you must ensure that the same instance of latch is used.
For more information go to nice tutorial: http://tutorials.jenkov.com/java-util-concurrent/countdownlatch.html

how to run the main thread after all child threads have completed there exceution

I have a requirement in which 28 threads have to complete some functionality. I have created these threads as in anonymous inner classes like :
Thread t=new Thread(new Runnable(){public void run()
{//code
}}
);
t.start();
Now I want that the further execution should start after all these threads have finished there work.
Note : I am confused about join() method as it makes my threads run sequentially.
So can anyone suggest me how can I make main thread run once these threads are done with work.
Note : I am confused about join() method as it makes my threads run sequentially.
It will do that if you have code like this:
for (Runnable runnable : runnables) {
Thread t = new Thread(runnable);
t.start();
t.join();
}
However, you can start all the threads you want to run in parallel, then call join on them all. For example:
List<Thread> threads = new ArrayList<>();
for (Runnable runnable : runnables) {
Thread t = new Thread(runnable);
t.start();
threads.add(t);
}
// Now everything's running - join all the threads
for (Thread thread : threads) {
thread.join();
}
// Now you can do whatever you need to after all the
// threads have finished.
There are many other approaches, of course - starting threads directly may well not be as suitable in your code as using a higher level abstraction; it depends on what you're trying to achieve. The above should work fine though - assuming all the Runnables are able to run in parallel without blocking each other through synchronization.
Make use of CountDownLatch.
public static void main(String... args) {
final CountDownLatch latch = new CountDownLatch(28);
for(int i=0;i<28;i++) {
Thread t=new Thread(new Runnable(){
public void run()
{
try {
//code
} finally {
latch.countDown();
}
}
});
t.start();
}
latch.await();
// Continue Code
}
Use a CountDownLatch and wait for all your threads to complete. :) .
PS : I gotto agree, using join() is also correct and more efficient.
example code :
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("t1 : " + i);
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("t2 : " + i);
}
}
});
t2.start();
t1.join();
t2.join();
System.out.println("main");
}
O/P :
t1 : 0
t1 : 1
t2 : 0
t1 : 2
t1 : 3
t2 : 1
t1 : 4
t1 : 5
t2 : 2
t1 : 6
t1 : 7
t2 : 3
t1 : 8
t1 : 9
t2 : 4
t2 : 5
t2 : 6
t2 : 7
t2 : 8
t2 : 9
main
According to the behaviour you're giving for join, I'm guessing you're starting and joining the threads within a single loop.
If you check the javadoc on this page, you'll note that a call to join will halt the execution of the calling thread until the other thread has finished executing.
You might want to keep an array or a list of threads when creating them, and starting them all in one loop, and only then joining them all.
Thread[] workers = new Thread[28];
for (int i = 0; i < workers.length; i++) {
workers[i] = new Thread { ... };
}
// Start running all threads
for (Thread worker: workers) {
worker.start();
}
// Make sure all threads are completed
for (Thread worker: workers) {
worker.join(); // if the worker already stopped, it'll return immediately.
}
// Now all threads have finished running and you can start post-processing
It's not the most elegant solution, but it'll do the trick.
As mentioned by others, you should probably use a CountDownLatch (haven't used one yet, so I can't provide feedback)
Edit: I've been beaten to it by Jon Skeet, sorry for the redundant answer...
CountDownLatch is better option.
I have created dummy program.
In this program I am sum 1000 number. I created 10 thread. In main thread I am doing dome of all child thread sum. you will get understand to simply viewing the code.
package Test1;
import java.util.concurrent.CountDownLatch;
class Sum extends Thread {
private int from;
private int to;
private int sum = 0;
CountDownLatch latch;
public int getSum() {
return sum;
}
public Sum(int from, int to, CountDownLatch latch) {
this.from = from;
this.to = to;
this.latch = latch;
}
public void run() {
for (int i = from; i < to; i++) {
sum += i;
}
latch.countDown();
}
}
public class Test5 {
public static void main(String[] args) throws InterruptedException {
int n = 1000;
int tn = 10;
int from = 1;
int to;
int sum = 0;
Sum[] sumArray = new Sum[tn];
final CountDownLatch latch = new CountDownLatch(tn);
for (int i = 0; i < tn; i++) {
to = from + n / tn;
Sum s = new Sum(from, to, latch);
sumArray[i] = s;
s.start();
from = to;
}
// Thread.sleep(1000);
latch.await();
for (int i = 0; i < tn; i++) {
sum += sumArray[i].getSum();
}
System.out.println(sum);
}
}

Categories