analysing the difference betweeen synchronize and lock [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am a newbie to the world of Threads and I am going through threads to latest util package reentrant lock mechanism, I was going through the basis differences between synchronize mechanism and the newly added lock mechanism , as in the article these were the differences..
Another significant difference between ReentrantLock and synchronized keyword is fairness. synchronized keyword doesn't support fairness. Any thread can acquire lock once released, no preference can be specified, on the other hand you can make ReentrantLock fair by specifying fairness property, while creating instance of ReentrantLock. Fairness property provides lock to longest waiting thread, in case of contention.Please if you could provide a small program which proves this point sp that I can grasp more
main difference between synchronized and ReentrantLock is ability to trying for lock interruptibly, and with timeout. Thread doesn't need to block infinitely, which was the case with synchronized, Please if you could provide a small program which proves this point sp that I can grasp more
One more worth noting difference between ReentrantLock and synchronized keyword in Java is, ability to interrupt Thread while waiting for Lock. In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock. Similarly tryLock() with timeout can be used to timeout if lock is not available in certain time period.Please if you could provide a small program which proves this point sp that I can grasp more
Guys could you please provide a small program which shows all these above three points
I have tried this program , please advise what changes need to be done in it to prove above 3 points..
public class ReentrantLockHowto {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
//Locking using Lock and ReentrantLock
public int getCount() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " gets Count: " + count);
return count++;
} finally {
lock.unlock();
}
}
//Implicit locking using synchronized keyword
public int getCountTwo() {
return count++;
}
public static void main(String args[]) {
final ThreadTest counter = new ThreadTest();
Thread t1 = new Thread() {
#Override
public void run() {
while (counter.getCount() < 6) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace(); }
}
}
};
Thread t2 = new Thread() {
#Override
public void run() {
while (counter.getCount() < 6) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
};
t1.start();
t2.start();
}
}
Output:
Thread-0 gets Count: 0
Thread-1 gets Count: 1
Thread-1 gets Count: 2
Thread-0 gets Count: 3
Thread-1 gets Count: 4
Thread-0 gets Count: 5
Thread-0 gets Count: 6
Thread-1 gets Count: 7

Related

Can we Access Synchronized method and an unsynchronized method of same instance from multiple threads at the same time?

It might seem to be a very naive question but I cannot find any concrete answer anywhere. I tried it even practically but since we cannot predict the behaviour of threads resource allocation in Java, it's really difficult to determine.
I just want to know if I can access a synchronized method and and unsynchronized method of a class at the same time from two different threads of same instance of that class ?
Don't see any problems. Try out this:
public class Main {
public static final SyncNotsynced sn = new SyncNotsynced();
public static void main(String[] args){
Thread t1 = new Thread(sn::synced);
Thread t2 = new Thread(sn::notsynced);
t1.start();
t2.start();
}
public static class SyncNotsynced {
public synchronized void synced(){
System.out.println(Thread.currentThread().getName() + " enter synced");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + " exit synced");
}
public void notsynced(){
System.out.println(Thread.currentThread().getName() + " enter notsynced");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + " exit notsynced");
}
}
}
or take look at the live example :). As you can see enterings of Thread 1 and Thread 2 are both happened before exiting:
Thread-0 enter synced
Thread-1 enter notsynced
Thread-0 exit synced
Thread-1 exit notsynced
For a formal explanation you can read JLS 17, but in short only one thread can enter a synchronized block on the same object monitor.
Btw, I used Thread.sleep because (emphasize mine):
Thread.sleep causes the currently executing thread to sleep
(temporarily cease execution) for the specified duration, subject to
the precision and accuracy of system timers and schedulers. The thread
does not lose ownership of any monitors, and resumption of execution
will depend on scheduling and the availability of processors on which
to execute the thread.

Printing a statement using threads in Java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am trying to print a statement in Java using threads, where each thread should print part of the statement. However, following code does not always output statement in correct order.
class NewThread implements Runnable {
String msg;
Thread t;
NewThread(String str) {
t = new Thread(this);
msg = str;
}
public void run() {
PrintMsg(msg);
}
synchronized void PrintMsg(String msg) {
System.out.println(msg);
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception");
}
System.out.println(msg);
notify();
}
}
class ThreadDemo {
public static void main(String args[]) {
NewThread t1, t2, t3;
t1 = new NewThread("Humphry Dumprey");
t2 = new NewThread("went to the hill");
t3 = new NewThread("to fetch a pail of water");
t1.t.start();
t2.t.start();
t3.t.start();
try {
t1.t.join();
t2.t.join();
t3.t.join();
} catch (InterruptedException e) {
System.out.println("Main Thread Interrupted");
}
}
}
I suspect problem with inter-thread communication.
I think your problem is in this method:
synchronized void PrintMsg(String msg) {
System.out.println(msg);
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception");
}
System.out.println(msg);
notify();
}
The thread that call it are going to call wait() which causes them to wait indefinitely for someone to call notify(). But there are no other calls to notify() so they all will stop there.
Also, because the method is synchronized each thread is also waiting on it's own NewThread instance. I think you meant to have all threads waiting and notifying on the same object?
From comments:
want to wait a thread until it finishes writing a part of statement. It should be like this : Thread 1 prints "Humphry Dumprey" Thread 2 prints "went to the hill" Thread 3 prints "to fetch a pail of water" and these three threads should execute in sequence such that the statement gets printed in right sequence.
I never understand these sorts of questions. The whole point of threads are that the run asynchronously in parallel. If you want them to print 3 things in a row then 1 thread should be used instead.
If you need to do this for some assignment then there a couple different ways you can do it.
Each thread could synchronize on the same AtomicInteger. Thread #1 would do its print if the integer was 1, thread #2 when it is 2, .... You could pass in the order as a value field to the NewThread constructor. After they print they values they increment the integer and notifyAll().
static final AtomicInteger counter = new AtomicInteger(1);
...
synchronized (counter) {
// looping like this is always recommended
while (counter.get() != value) {
counter.wait();
}
System.out.println(...);
counter.incrementAndGet();
counter.notifyAll();
}
You could use 2 CountdownLatch so thread #2 calls countDown1.await(); and thread #3 waits for countDown2.await();. Then after thread #1 prints its message it calls countDown1.countDown() and after thread #2 prints its message it calls countDown2.countDown().

Create a multithreaded program by creating a subclass of Thread and then creating, initializing, and starting two Thread objects from main class. [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Create a multithreaded program by creating a subclass of Thread and then creating, initializing, and starting two Thread objects from main class. The threads will execute the following output in the suitable interface.
OUTPUT :
thread1: Java
thread1: is
thread2: Java
thread1: an
thread2: is
thread1: exciting
thread2: an
thread1: new
thread2: exciting
thread1: language
thread1: for
thread1: concurrent
thread2: new
thread1: programming.
thread2: language
thread2: for
thread2: concurrent
thread2: programming.
this is my coding is seem to call thread 1 first then thread 2. How to make it display like that output.
class Thread1 extends Thread {
public void run() {
System.out.println("Thread1: Java");
System.out.println("Thread1: is ");
System.out.println("Thread1: exciting ");
System.out.println("Thread1: new ");
System.out.println("Thread1: language ");
System.out.println("Thread1: for ");
System.out.println("Thread1: concurrent ");
System.out.println("Thread1: programming ");
}
}
class Thread2 extends Thread {
public void run() {
System.out.println("Thread2 Java");
System.out.println("Thread2: an ");
System.out.println("Thread2: is ");
System.out.println("Thread2: an ");
System.out.println("Thread2: exciting");
System.out.println("Thread2: new");
System.out.println("Thread2: language");
System.out.println("Thread2: for");
System.out.println("Thread2: concurrent");
System.out.println("Thread2: programming");
suspend();
}
}
class Thread3 extends Thread
{
public void run()
{
System.out.print("Thread3");
try
{
sleep(1000);
}
catch(Exception e)
{
}
System.out.print(" Running");
}
}
class ThreadDemo3
{
public static void main(String args[]) throws InterruptedException
{
Thread1 obj1 = new Thread1();
obj1.start();
Thread2 obj2 = new Thread2();
obj2.start();
}
}
Execute it until you get the desired result.
No seriously, this a typical example to show that threads do NOT execute in a specific order.
So the output of your program should be different each time you run it (not predictable). But you try to do exactly that.
One solution could be to use a lock (see synchronized) that you acquire and release it when the other thread should do the job (remember to add some kind of wait to prevent the thread from instant reacquiring the lock), but this is counter productive here.
By the way: this looks for me like you copied your homework to SO.
Edit: Get an older Machine, where the first Thread is not yet finished when the new Thread starts.
Really, predicting the order in which the commands are executed is like playing roulette. You can try it, but at the end you will loose.
There is no non-messy way to do this madness. If I was forced to do it at gunpoint, I would probably have each thread run a switch/case state-machine and, when a thread-swapover is required, signal a semaphore to the other thread and wait on another semaphore for its state-machine to signal back.

Difference between notify() and notifyAll()

I know that similar questions have been discussed in this site, but I have not still got further by their aid considering a specific example. I can grasp the difference of notify() and notifyAll() regarding Thread "awakeining" in theory but I cannot perceive how they influence the functionality of program when either of them is used instead of the other. Therefore I set the following code and I would like to know what is the impact of using each one of them. I can say from the start that they give the same output (Sum is printed 3 times).
How do they differ virtually? How could someone modify the program, in order for the applying notify or notifyAll to play a crucial role to its functionality (to give different results)?
Task:
class MyWidget implements Runnable {
private List<Integer> list;
private int sum;
public MyWidget(List<Integer> l) {
list = l;
}
public synchronized int getSum() {
return sum;
}
#Override
public void run() {
synchronized (this) {
int total = 0;
for (Integer i : list)
total += i;
sum = total;
notifyAll();
}
}
}
Thread:
public class MyClient extends Thread {
MyWidget mw;
public MyClient(MyWidget wid) {
mw = wid;
}
public void run() {
synchronized (mw) {
while (mw.getSum() == 0) {
try {
mw.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Sum calculated from Thread "
+ Thread.currentThread().getId() + " : " + mw.getSum());
}
}
public static void main(String[] args) {
Integer[] array = { 4, 6, 3, 8, 6 };
List<Integer> integers = Arrays.asList(array);
MyWidget wid = new MyWidget(integers);
Thread widThread = new Thread(wid);
Thread t1 = new MyClient(wid);
Thread t2 = new MyClient(wid);
Thread t3 = new MyClient(wid);
widThread.start();
t1.start();
t2.start();
t3.start();
}
}
UPDATE:
I write it explicitly. The result is the same whether one uses notify or notifyAll:
Sum calculated from Thread 12 : 27
Sum calculated from Thread 11 : 27
Sum calculated from Thread 10 : 27
Therefore my question: What is the difference?
The difference is subtler than your example aims to provoke. In the words of Josh Bloch (Effective Java 2nd Ed, Item 69):
... there may be cause to use notifyAll in place of notify. Just as placing the wait invocation in a loop protects against accidental or malicious notifications on a publicly accessible object, using notifyAll in place of notify protects against accidental or malicious waits by an unrelated thread. Such waits could otherwise “swallow” a critical notification, leaving its intended recipient waiting indefinitely.
So the idea is that you must consider other pieces of code entering wait on the same monitor you are waiting on, and those other threads swallowing the notification without reacting in the designed way.
Other pitfalls apply as well, which can result in thread starvation, such as that several threads may wait for different conditions, but notify always happens to wake the same thread, and the one whose condition is not satisfied.
Even though not immediately related to your question, I feel it is important to quote this conclusion as well (emphasis by original author):
In summary, using wait and notify directly is like programming in “concurrency assembly language,” as compared to the higher-level language provided by java.util.concurrent. There is seldom, if ever, a reason to use wait and notify in new code. If you maintain code that uses wait and notify, make sure that it always invokes wait from within a while loop using the standard idiom. The notifyAll method should generally be used in preference to notify. If notify is used, great care must be taken to ensure liveness.
This is made clear in all sorts of docs. The difference is that notify() selects (randomly) one thread, waiting for a given lock, and starts it. notifyAll() instead, restarts all threads waiting for the lock.
Best practice suggests that threads always wait in a loop, exited only when the condition on which they are waiting is satisfied. If all threads do that, then you can always use notifyAll(), guaranteeing that every thread whose wait condition has been satisfied, is restarted.
Edited to add hopefully enlightening code:
This program:
import java.util.concurrent.CountDownLatch;
public class NotifyExample {
static final int N_THREADS = 10;
static final char[] lock = new char[0];
static final CountDownLatch latch = new CountDownLatch(N_THREADS);
public static void main(String[] args) {
for (int i = 0; i < N_THREADS; i++) {
final int id = i;
new Thread() {
#Override public void run() {
synchronized (lock) {
System.out.println("waiting: " + id);
latch.countDown();
try { lock.wait(); }
catch (InterruptedException e) {
System.out.println("interrupted: " + id);
}
System.out.println("awake: " + id);
}
}
}.start();
}
try { latch.await(); }
catch (InterruptedException e) {
System.out.println("latch interrupted");
}
synchronized (lock) { lock.notify(); }
}
}
produced this output, in one example run:
waiting: 0
waiting: 4
waiting: 3
waiting: 6
waiting: 2
waiting: 1
waiting: 7
waiting: 5
waiting: 8
waiting: 9
awake: 0
None of the other 9 threads will ever awaken, unless there are further calls to notify.
notify wakes (any) one thread in the wait set, notifyAll wakes all threads in the waiting set. notifyAll should be used most of the time. If you are not sure which to use, then use notifyAll.
In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use notifyAll() to wake up all waiting threads at the same time.
Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use notify(). Properly implemented, you could use notifyAll() in this situation as well, but you would unnecessarily wake threads that can't do anything anyway.
Javadocs on notify.
Javadocs on notifyAll.
Once only one thread is waiting to sum to not be zero, there is no difference. If there are several threads waiting, notify will wake up only one of them, and all the other will wait forever.
Run this test to better understand the difference:
public class NotifyTest implements Runnable {
#Override
public void run ()
{
synchronized (NotifyTest.class)
{
System.out.println ("Waiting: " + this);
try
{
NotifyTest.class.wait ();
}
catch (InterruptedException ex)
{
return;
}
System.out.println ("Notified: " + this);
}
}
public static void main (String [] args) throws Exception
{
for (int i = 0; i < 10; i++)
new Thread (new NotifyTest ()).start ();
Thread.sleep (1000L); // Let them go into wait ()
System.out.println ("Doing notify ()");
synchronized (NotifyTest.class)
{
NotifyTest.class.notify ();
}
Thread.sleep (1000L); // Let them print their messages
System.out.println ("Doing notifyAll ()");
synchronized (NotifyTest.class)
{
NotifyTest.class.notifyAll ();
}
}
}
I found what is going on with my program. The three Threads print the result even with the notify(), because they do not manage to enter the waiting state. The calculation in the widThread is performed quickly enough to preempt the entering of the other Threads in the waiting state, since it depends on the condition mw.getSum() == 0 (while loop). The widThread calculates the sum, so that the remaining Threads do not ever "see" its value as 0.
If the while loop is removed and the start of widThread comes after the start of the other Threads, then by notify() only one Thread prints the result and the others are waiting forever, as the theory and the other answers indicate.

Why is this code deadlocking? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I need some help concerning deadlocks. I just do not understand why my code is deadlocking here.
I tried different scenarios.
However I still can't find why and where is the problem. Normally it should work
and I don't find where the deadlock is between debuter and termine.
public class Interblocking {
protected object obj = object();
private boolean condition = true;
public synchronized void debuter() {
synchronized(obj) {
while (!condition) {
try {
obj.wait();
} catch (InterruptedExeption ie) {}
}
condition = false;
}
}
public synchronized void terminer() {
synchronized(obj) {
condition = true;
obj.notifyAll();
}
}
}
Edit (new answer)
Method wait() doesn't release all locks of current Thread.
So when A thread invokes debuter it releases only obj lock but holds this lock so other threads can't invoke terminer method.
Here is example:
class WaitReleaseTest implements Runnable {
Object lockA, lockB;
public WaitReleaseTest(Object lockA, Object lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
public void run() {
System.out.println(Thread.currentThread().getName()
+ " attempting to acquire lockA");
synchronized (lockA) {
System.out.println(Thread.currentThread().getName()
+ " attempting to acquire lockB");
synchronized (lockB) {
System.out.println(Thread.currentThread().getName()
+ " holds lockA = " + Thread.holdsLock(lockA));
System.out.println(Thread.currentThread().getName()
+ " holds lockB = " + Thread.holdsLock(lockB));
try {
lockB.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Object o1=new Object();
Object o2=new Object();
new Thread(new WaitReleaseTest(o1,o2)).start();
TimeUnit.MILLISECONDS.sleep(500);
new Thread(new WaitReleaseTest(o1,o2)).start();
}
}
output
Thread-0 attempting to acquire lockA
Thread-0 attempting to acquire lockB
Thread-0 holds lockA = true
Thread-0 holds lockB = true
Thread-1 attempting to acquire lockA
... now it waits
The code does not contain deadlock conditions. Deadlocks occur when there are cycles in the graph of resources. You have only one resource (obj) so the resource graph consists of single node and cannot contain cycles.
While debuter may wait forcondition, terminer never waits for long time.
I guess your code is total different from what your code is able to do.
You probably want a thread entering debuter to wait until condition is to true;
The basic problem are the synchronized keyword on the method. They assure that only thread is in any method of your instance of Interblocking
Remove synchronized on the methods.
The next problem is condition. It is undefined how may thread becomes released after called terminer
You run into a dead lock on the second call to debuter because condition is false after the first call to debuter.
And there is no way to execute terminer because there is a thread in debuter blocking
Using multiple levels of blocking objects (in this case object and this) is always suspicious to cause a dead lock.

Categories

Resources