Concurrent Threads - java

I completed some basic code to assign 2 threads a task. But I have to make 2 versions where one can have both threads invoke the task concurrently, and one where it would never be concurrent. But I'm not even sure which version I have made, let alone how I would identify it.
import java.util.*;
public class Week5
{
static int sharedData = 0;
public static void main(String[] args)
{
atomic myAtomic = new atomic();
Thread thread1 = new Thread(myAtomic);
thread1.setName("thread 1");
Thread thread2 = new Thread(myAtomic);
thread2.setName("thread 2");
thread1.start();
thread2.start();
try
{
thread1.join();
thread2.join();
}
catch(InterruptedException e)
{
System.out.println("Thread " + Thread.currentThread().getName() + "was interrupted");
}
System.out.println("sharedData = " + sharedData);
System.out.println("Exiting Main function from: " + Thread.currentThread().getName());
}
public static class atomic implements Runnable
{
public synchronized void run()
{
System.out.println("Starting 'Atomic' Function from: " + Thread.currentThread().getName());
sharedData = sharedData + 1;
System.out.println("Exiting 'Run' function from: " + Thread.currentThread().getName());
}
}
}

Your threads can never run the same task concurrently, because the run() method is synchronized, meaning only one thread can enter at a time for the same object. If it were not synchronized, both threads could potentially execute it simultaneously.

Related

Creating my own Java deadlock program

I was trying to create A Java dead lock program . I know in real time we wont be creating any dead lock in thread. Unfortunately I have been asked in one of the interview to writing a "Deadlock program using two threads". So here it is
package Thread.DeadLock;
public class deadLock2 {
static ThreadSample1 t1 = new ThreadSample1();
static ThreadSample2 t2 = new ThreadSample2();
public static void main(String args[]) {
t1.start();
t2.start();
}
public static class ThreadSample1 extends Thread {
public void run() {
System.out.println("In first run method");
try {
System.out.println("Holding lock in first one");
synchronized (t1) {
System.out.println("t1 going to wait for t2");
t1.wait();
System.out.println("t1 finished for waiting");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static class ThreadSample2 extends Thread {
public void run() {
System.out.println("In second run method");
try {
System.out.println("Holding lock for second one");
synchronized (t2) {
System.out.println("t2 going to wait for t1");
t2.wait();
System.out.println("t2 finished for waiting");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I can see the program is getting stuck. I am assuming that it in deadlock situation. t1.start() waits for t2 to finish its task and t2.start() waits for t1 to finish its task. Now while I try to remove the deadlock by notifying the waiting thread using using t1.notify() I get IllegalMonitorStateException.
Can somebody tell in this situation how to remove the deadlock without causing any situation.
First, this is not deadlock. As you correctly described, deadlock is usually situation when there is circular dependency between two or more threads waiting for resources that is held by other thread.
Here, each thread independently waits for notification on itself which is actually not delivered by anybody else in the system. Even if there is no deadlock.
Secondly, IllegalMonitorStateException means that you try to notify/wait on monitor which is not held by the thread. In other words, there is no synchronized prior to notify/wait.
Third, to achieve real deadlock you can do something like this:
synchronized(t1) {
synchronized(t2) {
t2.wait();
}
t1.notify();
}
and vice versa for the other thread.
You can not call notify()/notifyAll() unless the current thread owns that object's monitor. To do that, you must synchronize on it, as you did with wait()
The Javadocs for wait() mention this:
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws:
IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.
And from notify():
A thread becomes the owner of the object's monitor in one of three
ways:
By executing a synchronized instance method of that object.
By executing the body of a synchronized statement that synchronizes on the object.
For objects of type Class, by executing a synchronized static method of that class.
See this answer:
Java Wait and Notify: IllegalMonitorStateException
package pck.pramod.geekforgeeks;
public class ThreadDeadlock {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
System.out.println(Lock1.toString() + " " + Lock2.toString());
ThreadDemo1 T1 = new ThreadDemo1(Lock1, Lock2, "T1");
ThreadDemo1 T2 = new ThreadDemo1(Lock2, Lock1, "T2");
T1.start();
T2.start();
}
}
class ThreadDemo1 extends Thread {
Object lock1;
Object lock2;
String name;
public ThreadDemo1(Object lock1, Object lock2, String name) {
this.lock1 = lock1;
this.lock2 = lock2;
this.name = name;
}
public void run() {
synchronized (lock1) {
System.out.println(name + " Holding lock ..." + lock1.toString());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println(name + " Waiting for lock ..." + lock2.toString());
synchronized (lock2) {
System.out.println(name + " Holding lock ..." + lock1.toString() + " " + lock2.toString());
}
}
}
}

Class level lock for static variables in java

If i don't use any setters/getters in my java class X. When a thread A has class level lock of my class X. Can another thread B change my static variable directly ??
public class X {
Integer static_variable = 10;
public static void doNothing {
/* Do Nothing */
}
}
Lets say thread A has class level lock now. Can i do X.static_variable = 11 from another thread B?
I was writing a code to get deadlock in java.
public class A implements Runnable {
public static Integer as = 5;
static A a = new A();
static B b = new B();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Thread thread1 = new Thread(a);
Thread thread2 = new Thread(b);
thread1.setName("First");
thread2.setName("Second");
thread1.start();
thread2.start();
}
public void run() {
runme();
}
public static synchronized void runme() {
try {
System.out.println(Thread.currentThread().getName() + " has object a's key and waiting");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " Woke up from sleep");
System.out.println(Thread.currentThread().getName() + " wants b's Key");
B.bs = 10;
System.out.println(Thread.currentThread().getName() + " over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class B implements Runnable {
public static Integer bs = 6;
public void run() {
runme();
}
public static synchronized void runme() {
try {
System.out.println(Thread.currentThread().getName() + " has object b's key and waiting");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " Woke up from sleep");
System.out.println(Thread.currentThread().getName() + " wants a's Key");
A.as = 10;
System.out.println(Thread.currentThread().getName() + " over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
But getting below result:
Second has object b's key and waiting
First has object a's key and waiting
First Woke up from sleep
Second Woke up from sleep
Second wants a's Key
Second over
First wants b's Key
First over
Second thread is clearly editing the static variable of class A even when another thread holds the class level lock of class A
Yes you can. Unless you have a synchronized block around the variable changing code. If you don't use synchronization, other threads don't have to acquire the X.class's monitor before changing its static_variable.
Make the field private, and add a setter, make it synchronized, then you will not be able to change the field when another thread holds the lock for X.class

Purpose of Thread constructor arguments

I found this code on a tutorial website:
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
In the following line, what is the purpose of the arguments, and what is the meaning of this in the first argument:
t = new Thread(this, "Demo Thread");
Also, what is the expected behaviour (flow) of this code?
When creating a new Thread object you must pass in a Runnable object (which does the actual work in its run() method) as the first argument to the constructor. The second argument is a name for the thread. So, in your code, the following line in the NewThread class constructor:
t = new Thread(this, "Demo Thread");
Creates a new Thread object t named Demo Thread using itself (an instance of NewThread) as the Runnable task, since it implements the Runnable interface. Then, when t.start() is called, the run() method of the NewThread instance t is called.
The API documentation for java.lang.Thread and java.lang.Runnable give more details.
So, your code creates a NewThread object, which starts a child thread in the constructor running the Child Thread loop, and the Main Thread loop is executed by the rest of the code in your main() method. I would expect to see output from the child thread interleaved with output from the main thread when this is run.
Also, when catching InterruptedException and not re-throwing it, it is good practice to restore the interrupted status of the thread, something like this:
} catch (InterruptedException ie) {
System.out.println("Interrupted: " + ie.getMessage());
Thread.currentThread().interrupt();
}
This tutorial by Brian Goetz is very good if you want to learn more about Java threading. It's part of an IBM developerWorks Java concurrency training module.
The line t = new Thread(this, "Demo Thread") is creating a new thread passing the instance of java.lang.Runnable that the thread should execute and the name to give the thread (commonly used during logging operations).
It's a bit weird to have the class implementing java.lang.Runnable create the thread itself. Take a look at the examples of how to use threads on the JavaDoc for java.lang.Thread.
The constructor used in t = new Thread(this, "Demo thread") allows to pass a target. The target must be a Runnable. The target's run() method will be invoked as a result of starting t, so the Thread is created and runs. See the documentation
That's some seriously messed up code up there. OP, you did not write this, but you'll take heat just for stumbling on it.
First of all: The NewThread is not a thread, it's a Runnable. Not the same thing, and for a reason. But then its constructor declares a new thread and starts it right away, turning the Runnable into some sort of a Zombie Thread, which defeats the whole purpose of having a Runnable in the first place, and is just a terrible idea, because if you wanted a Thread, you'd declare a Thread, not a Runnable. What if you want to use the Runnable in a ThreadPool? What if you want to define more than one of these Runnables and start them in a orderly fashion? What if the Runnable one day becomes a Callable, where would you see its Future?
Then, to add insult to injury, the code has concurrent code in the main thread. This servers no educational purpose, and has almost no real-life value, because in real life, you normally don't mix threaded code like that, you'd rather have one control thread (main) and 1..n worker threads (controlled by main).
The point of Threads and Runnables is to separate the functional description of the task (that's the Runnable) from the life-cycle behavior (that's the Thread). Parallel execution and scalability is a nice side benefit. So let's refactor the tutorial code to reflect that:
class Countdown implements Runnable {
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo2 {
public static void main(String args[]) {
Thread t = new Thread(new Countdown());
t.start();
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
That's better. Now the Runnable does no longer pretend to be a Thread, nor does it even care about when or how or by whom it is going to be run. All it does is implement run() which does what the task is supposed to do, and the main thread gives this Runnable as a constructor argument to a new Thread and then start()s it, which in turn means the new Thread will call the Runnable's run(). But we can do better: the two threads do essentially the same thing, so we should implement them that way:
class Countdown implements Runnable {
final String name;
final int length;
final int skip;
public Countdown(String name, int length, int skip) {
this.name = name;
this.length = length;
this.skip = skip;
}
public void run() {
try {
for(int i = length; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(skip);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println("Exiting " + name);
}
}
public class ThreadDemo3 {
public static void main(String args[]) {
Thread t1 = new Thread(new Countdown("Child One", 5, 50));
Thread t2 = new Thread(new Countdown("Child Two", 5, 100));
t1.start();
t2.start();
}
}
Now we have separated functionality from life-cycle management. Countdown is it's own class which does exactly what the name says and not more, and there is no more worker logic in main. Main just invokes countdowns and starts them.
OP, my biggest advice is: find a better tutorial. The Brian Goetz tutorial mentioned by grkvlt above is much better. You might want to invest some money on books by Goetz ("Java Concurrency in Practice") and Doug Lea ("Concurrent Programming in Java"), too.

Child thread synchronization is not working here

Java Code:
// Create a second thread.
class NewThread implements Runnable
{
Thread t;
NewThread()
{
t = new Thread(this, "Demo Thread"); // Create a new, second thread
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
public void run() // This is the entry point for the second thread.
{
justCall();
}
public synchronized void justCall()
{
try
{
for(int i = 10; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(10000);
}
}
catch (Exception e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo
{
public static void main(String args[])
{
NewThread nt = new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
here you can delete the synchronized justCall() method and you can initialize a synchronization block in a run() method(put justCall() method's code in a synchronized block).
How to synchronize child code here? Please Help. I read that Thread.sleep() method never releases the lock while it is executing in the synchronization block or method. But in my code main thread and child code executes concurrently. Please help to synchronize the child code using Thread.sleep() method.
When two threads synchronize on the same object, they will not both run that same code. This allows many different threads to cooperate running in many different areas of code at the same time.
A synchronized on a non-static method creates a lock on the this object. If it had been a static method the lock would have been on the Class object for the NewThread class. Any class and any instance of any class can have a syncronized on it and thus create a lock.
You have only one thread running in the synchronized area. So, while it is locked, no other thread is attempting to run the locked code. No other thread is attempting to synchronize on the nt instance of the NewThread class.
You might want to try doing this:
NewThread nt1 = new NewThread(); // create a new thread
NewThread nt2 = new NewThread(); // create a 2nd new thread
Then leave off the looping in the main class.

Synchronization with threads

I have a two part question...
I have a class with a function in it that can only be accessed by any one thread at a given time. Making this a synchronized function or a synchronized block still allows for multiple threads since different threads are accessing it within the class. How can I make sure only one thread accesses this code? (See code example below)
With the synchronized function, the calls to the function are queued up. Is there any way to only allow the last call to the function to access the code? So if I have Thread1 currently accessing my function, then Thread2 and Thread3 try to access it (in that order) only Thread3 will be given access once Thread1 is complete.
public void doATask() {
// I create a new thread so the interface is not blocked
new Thread(new Runnable() {
#Override
public void run() {
doBackgroundTask();
}
}).start();
}
private void doBackgroundTask(MyObject obj) {
// perform long task here that is only being run by one thread
// and also only accepts the last queued thread
}
Thanks for any help!
If the second thread in your example can just return, you could use a combination of a lock and keeping track of the last thread executing the method. It could look like this:
private volatile Thread lastThread;
private final ReentrantLock lock = new ReentrantLock();
private void doBackgroundTask(Object obj) throws InterruptedException {
Thread currentThread = Thread.currentThread();
lastThread = currentThread;
try {
// wait until lock available
lock.lockInterruptibly();
// if a thread has arrived in the meantime, exit and release the lock
if (lastThread != currentThread) return;
// otherwise
// perform long task here that is only being run by one thread
// and also only accepts the last queued thread
} finally {
lock.unlock();
}
}
Full working test with additional logging that shows the thread interleaving and that T2 exits without doing nothing:
class Test {
private volatile Thread lastThread;
private final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws Exception {
final Test instance = new Test();
Runnable r = new Runnable() {
#Override
public void run() {
try {
instance.doBackgroundTask(null);
} catch (InterruptedException ignore) {}
}
};
Thread t1 = new Thread(r, "T1");
Thread t2 = new Thread(r, "T2");
Thread t3 = new Thread(r, "T3");
t1.start();
Thread.sleep(100);
t2.start();
Thread.sleep(100);
t3.start();
}
private void doBackgroundTask(Object obj) throws InterruptedException {
Thread currentThread = Thread.currentThread();
System.out.println("[" + currentThread.getName() + "] entering");
lastThread = currentThread;
try {
// wait until lock available
lock.lockInterruptibly();
// if a thread has arrived in the meantime, exit and release the lock
if (lastThread != currentThread) return;
// otherwise
// perform long task here that is only being run by one thread
// and also only accepts the last queued thread
System.out.println("[" + currentThread.getName() + "] Thinking deeply");
Thread.sleep(1000);
System.out.println("[" + currentThread.getName() + "] I'm done");
} finally {
lock.unlock();
System.out.println("[" + currentThread.getName() + "] exiting");
}
}
}
Output:
[T1] entering
[T1] Thinking deeply
[T2] entering
[T3] entering
[T1] I'm done
[T1] exiting
[T2] exiting
[T3] Thinking deeply
[T3] I'm done
[T3] exiting
What you want is probably a worker thread that waits for a signal to do some work. doATask() simply sends a signal to trigger the work. Accumulative signals are equivalent to one signal.
final Object lock = new Object();
MyObject param = null;
public void doATask(arg)
synchronized(lock)
param=arg;
lock.notify();
MyObject awaitTask()
synchronized(lock)
while(param==null)
lock.wait();
tmp=param;
param=null;
return tmp;
// worker thread
public void run()
while(true)
arg = awaitTask();
doBackgroundTask(arg);

Categories