why this thread is not safe - java

Example One:
public class Test {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
Runnable t1 = new MyRunnable("A", 2000);
Runnable t2 = new MyRunnable("B", 3600);
Runnable t3 = new MyRunnable("C", 2700);
Runnable t4 = new MyRunnable("D", 600);
Runnable t5 = new MyRunnable("E", 1300);
Runnable t6 = new MyRunnable("F", 800);
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
pool.shutdown();
}
}
class MyRunnable implements Runnable {
private static AtomicLong aLong = new AtomicLong(10000);
private String name;
private int x;
MyRunnable(String name, int x) {
this.name = name;
this.x = x;
}
public void run() {
System.out.println(name + " excute" + x + ",money:" + aLong.addAndGet(x));
}
}
this thread is not safe in this sample.
Example Two
public class CountingFactorizer implements Servlet {
private final AtomicLong count = new AtomicLong(0);
public void service(ServletRequest req, ServletResponse resp) {
count.incrementAndGet();
}
}
why is this thread safe? somebody can tell me?
I'm study thread in java, but cannot understand two sample. Are they different?

As far I can see both are thread safe. In both examples the static, class level, member is AtomicLong that is thread safe by definition. All other members in the first example are instance level member and are executed in different threads, so no conflicts at all.

Related

Passing command-line arguments to mutliple java threads

I'm trying to create multiple threads in a java program and have them perform arithmetic operations on integers passed as command-line arguments. Obviously neither of the thread classes I'm trying to pass to are in the main method so how can I still access a variable like args[0] from these classes?
public class Mythread {
public static void main(String[] args) {
Runnable r = new multiplication();
Thread t = new Thread(r);
Runnable r2 = new summation();
Thread t2 = new Thread(r2);
t.start();
t2.start();
}
}
class summation implements Runnable{
public void run(){
System.out.print(args[0]);
}
}
class multiplication implements Runnable{
public void run(){
System.out.print(args[1]);
}
}
You should pass in the necessary information in the constructor
class Summation implements Runnable {
private final String info;
public Summation(String info) {
this.info = info;
}
#Override
public void run(){
System.out.print(info);
}
}
Then you can pass in the args values to your threads in main so that you have them in your runnables / threads
public class Mythread {
public static void main(String[] args) {
Runnable r = new multiplication(args[1]);
Thread t = new Thread(r);
Runnable r2 = new summation(args[0]);
Thread t2 = new Thread(r2);
t.start();
t2.start();
}
}

threading using extend Thread

I can get my method threadR to run by a runnable thread, however i cant seem to get threadL to run as a thread and print out to the console
System.out.println("Greetings from Fred! threadL"); from my run thread
What am i doing wrong?
package threads;
import java.util.ArrayList;
import java.util.List;
public class Threads extends Thread implements Runnable {
private final List<Thread> threadList = new ArrayList<>();
private String e,l;
private Thread greetings;
public static void main(String[] args) {
String[] elements = {"Tim","Fred"};
Threads t = new Threads();
for (String e: elements) {
t.threadL(e);
t.threadR(e);
}
for(int index = 0;index<t.threadList.size();index++){
System.out.print(t.threadList.get(index).getName()+ " ID "+ t.threadList.get(index).getId()+"\n");
}
}
public List<Thread> threadL(String l) {
Thread greetings1 = new Thread(l);
greetings1.start();
threadList.add(greetings1);
//System.out.print(greetings.getName()+"\n");
//System.out.print(greetings.getId()+"\n");
return(threadList);
}
public List<Thread> threadR(String f) {
greetings = new Thread(f);
Thread greetingsFromFred = new Thread(greetings) {
#Override
public void run() {
System.out.println("Greetings from Fred! threadR");
}
}; greetingsFromFred.start();
threadList.add(greetings);
//System.out.print(greetings.getName()+"\n");
//System.out.print(greetings.getId()+"\n");
return(threadList);
}
public void run() {
System.out.println("Greetings from Fred! threadL"); //this is what wont run
}
When you pass a String as the only argument to new Thread(String); you are actually setting the Thread name. You probably meant to pass a Runnable to the Thread as such
Thread greetings1 = new Thread(this);
Thread Constructors

Java multi-threads programming

I am a beginner of Java programming learner. I can't know how to correct the following Java program. Kindly help to let me know how to correct it. Thanks a lot.
public class TMA1Q2 {
public static void main(String[] args) {
System.out.println("Usage: java TMA1Q2 {number of Threads}");
// Create tasks
Runnable taskA = new PrintTwoConcurThreads("Thread A ");
Runnable taskB = new PrintTwoConcurThreads(" Thread B ");
// Create threads
Thread thread1 = new Thread(taskA);
Thread thread2 = new Thread(taskB);
// Start threads
thread1.start();
thread2.start();
}
}
// The task that implements Runnable
class PrintTwoConcurThreads implements Runnable {
private final String TwoConcurThreads;
private String[] args;
public PrintTwoConcurThreads(String numThreads) {
TwoConcurThreads = numThreads;
}
// Override the run() method
#Override
public void run() {
// Print the value input argument times
int numThreads = Integer.parseInt(args[0]);
Thread[] myThread;
myThread = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
System.out.println(TwoConcurThreads + i);
}
}
}
private String[] args;
This args field is never initialized, so it will be having a default value of null.
When you try to access it in following line you get a NullPointerException
int numThreads = Integer.parseInt(args[0]);
It is not clear what you're trying to do. Atleast this would help you to see what's going wrong.
Also I have no Idea why following lines are used, You create Thread[] but never you used it.
Thread[] myThread;
myThread = new Thread[numThreads];

Regarding countdown latch implementation

I have been going through the program which starts three threads and print their corresponding value such that T3 is executed first, then the T1 thread, and lastly the T2 thread is executed. Below is the program.
I just want to know if you guys could help in converting this program with respect to countdown latch, as I want to develop it using this mechanism or it can be also done through counting semaphore.
From the answer to this related question:
public class Test {
static class Printer implements Runnable {
private final int from;
private final int to;
private Thread joinThread;
Printer(int from, int to, Thread joinThread) {
this.from = from;
this.to = to;
this.joinThread = joinThread;
}
#Override
public void run() {
if(joinThread != null) {
try {
joinThread.join();
} catch (InterruptedException e) { /* ignore for test purposes */ }
}
for (int i = from; i <= to; i++) {
System.out.println(i);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread T3 = new Thread(new Printer(10, 15, null));
Thread T1 = new Thread(new Printer(1, 5, T3));
Thread T2 = new Thread(new Printer(6, 10, T1));
T1.start();
T2.start();
T3.start();
}
}
We consider each pair of threads Tw, Ts such as Tw is waiting on Ts to commence its work. In your setup, there are 2 such pairs:
T1, T3
T2, T1
For each pair, we will create one CountDownLatch, and provide it to each thread of the pair. Then Tw will call await on the latch before starting its work, and Ts will call countDown at the end of its own work.
Since T1 belongs to both pairs, it will receive both latches. However, in the first case, T1 is a waiting thread, and in the second, T1 is a signaling thread, therefore its code will have to be amended accordingly.
Of course you will have to remove the join calls and related infrastructure.
Since your question title asks about latch implementation, let's just briefly say that the same semantics can be produced using a Semaphore initialized at 0, and where countDown would actually be a release of the semaphore, while await would be an acquire of that semaphore.
public class Test {
private CountdownLatch latch;
private Runnable runnable;
class Tw implements Runnable {
Tw(CountdownLatch l, Runnable r) {
latch = l;
runnable = r;
}
#override
public void run(){
latch.await();
runnable.run();
}
}
class Ts implements Runnable {
CountdownLatch latch;
Runnable runnable;
Ts(CountdownLatch l, Runnable r){
latch = l;
runnable = r;
}
#override
public void run(){
runnable.run();
latch.countDown();
}
}
static class Printer implements Runnable {
private final int from;
private final int to;
Printer(int from, int to) {
this.from = from;
this.to = to;
}
#Override
public void run() {
for (int i = from; i <= to; i++) {
System.out.println(i);
}
}
public static void main(String[] args) throws InterruptedException {
CountdownLatch l31 = new CountdownLatch(1), l12 = new CountdownLatch(1);
Thread T3 = new Thread(new Ts(l31, new Printer(10, 15, null)));
Thread T1 = new Thread(new Tw(l31, new Ts(l12, new Printer(1, 5, T3))));
Thread T2 = new Thread(new Tw(l12, new Printer(6, 10, T1)));
T1.start();
T2.start();
T3.start();
}
}
The proposed sample implementation uses auxiliary runnables to take care of the latching process, thus allowing us to compose each task using these runnables, instead of deriving the Printer class for each specific case (we save at least one class).
The Semaphore based similar implementation is left as an exercise for the reader.

ThreadLocal pondering (Or: Is sun's javadoc wrong?)

I've been reading about ThreadLocal, trying to understand how it works and why we need it.
So far what I've been able to learn is the following:
ThreadLocal class allows to hold 1 instance of an object at the thread level
The instance is created by overriding initialValue()
The instance is actually stored in the each thread's HashMap
A common sense usage example can be found here
All seemed fine, until I tried to run the example from the javadoc, the code is provided as following:
import java.util.concurrent.atomic.AtomicInteger;
public class UniqueThreadIdGenerator {
private static final AtomicInteger uniqueId = new AtomicInteger(0);
private static final ThreadLocal < Integer > uniqueNum =
new ThreadLocal < Integer > () {
#Override protected Integer initialValue() {
return uniqueId.getAndIncrement();
}
};
public static int getCurrentThreadId() {
return uniqueId.get();
}
} // UniqueThreadIdGenerator
If I understand this code correctly, calling getCurrentThreadId() should return the correct auto incremented thread number, alas it returns 0 for me. ALWAYS 0, without consideration of how many threads I have started.
To get this working for me I had to change getCurrentThreadId() to read
public static int getCurrentThreadId() {
return uniqueId.get();
}
In which case I am getting correct values.
My code is provided below, what am I missing? (It's not that the javadoc is actually wrong, right??)
package org.vekslers;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class UniqueThreadIdGenerator extends Thread {
private static final AtomicInteger uniqueId = new AtomicInteger(0);
private static final ThreadLocal <Integer> uniqueNum =
new ThreadLocal <Integer> () {
#Override protected Integer initialValue() {
return uniqueId.getAndIncrement();
}
};
public static int getCurrentThreadId() {
return uniqueNum.get();
}
//////////////////////////////////////////////////
// Testing code...
//////////////////////////////////////////////////
private static volatile boolean halt = false;
public UniqueThreadIdGenerator(String threadName) {
super(threadName);
}
#Override
public void run() {
System.out.println(Thread.currentThread() + " PREHALT " + getCurrentThreadId());
while(!halt)
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread() + " POSTHALT " + getCurrentThreadId());
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new UniqueThreadIdGenerator("t1");
Thread t2 = new UniqueThreadIdGenerator("t2");
Thread t3 = new UniqueThreadIdGenerator("t3");
Thread t4 = new UniqueThreadIdGenerator("t4");
t3.start();
t1.start();
t2.start();
t4.start();
TimeUnit.SECONDS.sleep(10);
halt = true;
}
} // UniqueThreadIdGenerator
Output:
Thread[t3,5,main] PREHALT 0
Thread[t1,5,main] PREHALT 1
Thread[t2,5,main] PREHALT 2
Thread[t4,5,main] PREHALT 3
Thread[t4,5,main] POSTHALT 3
Thread[t2,5,main] POSTHALT 2
Thread[t1,5,main] POSTHALT 1
Thread[t3,5,main] POSTHALT 0
p.s. Code comments OT or to the point are welcome in comments.
The javadocs are wrong.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6475885
Java 7's javadoc includes
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
#Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}

Categories

Resources