class Caller extends Thread
{
String s;
Caller(String s)
{
this.s=s;
}
void call(String msg)
{
synchronized (this)
{
System.out.print("["+msg);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("]");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public void run()
{
call(s);
}
}
public class SynchronisedBlock {
public static void main(String[] args) {
Caller c=new Caller("hi");
Caller c1=new Caller("li");
Caller c2=new Caller("wi");
c.start();
c1.start();
c2.start();
}
}
public class SynchronisedBlock {
public static void main(String[] args) {
Caller c=new Caller("hi");
Caller c1=new Caller("li");
Caller c2=new Caller("wi");
c.start();
c1.start();
c2.start();
}
}
I am trying to get synchronized access to call() using synchronized block but not getting that feature.When I am putting call() method in another class then I am getting the required functionality but not in this code. What am I missing? Can anyone tell me why? Thanx in advance.
As #svasa has stated, you need to have a common synchronizing object.
The simplest working example for your code would be to use a shared lock object. Also, the lock is final to prevent it from being replaced somewhere else in the code, you would end up synchronizing on different objects. (thanks to #P.J.Meisch):
class Caller extends Thread {
String s;
private static final Object lock = new Object();
Caller(String s) {
this.s = s;
}
void call(String msg) {
synchronized (lock) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("]");
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
}
}
public void run() {
call(s);
}
If your run method were in a Runnable like it's supposed to be, instead of a Thread, which it's not, then you could pass the same Runnable instance to each thread and this would work as a synchronization object reference.
Related
I am trying to learn java concurrency programming. Kindly check my sample code and help me understanding why I'm getting "java.lang.IllegalMonitorStateException" even though I have called wait() and notify in a synchronized context.
public class Test {
public static void main(String[] args) throws Exception {
Test t1 = new Test();
t1.m1();
}
private void m1() {
Example ex = new Example();
Thread t1 = new Thread(ex);
t1.start();
synchronized (ex) {
System.out.println("waiting");
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Example implements Runnable {
#Override
public void run() {
System.out.println("Running");
notifyMethod();
}
private void notifyMethod() {
System.out.println("Notifying");
synchronized (this) {
try {
Thread.sleep(1000);
} catch (Exception ex) {
ex.printStackTrace();
}
notify();
}
}
}
}
I expect out of "waiting,running,notifying" but the actual output is:
waiting
Running
java.lang.IllegalMonitorStateException
Notifying
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at examples.Test.m1(Test.java:18)
at examples.Test.main(Test.java:8)
First of, I think synchonizing on a Runnable isn't a good idea (Example in your case). You either synchonize on this or, even better, on a dedicated Object, that is lock in my example. Edit: Synchronizing on a Runnable is the same as using this but for me it looks better. Guts tell me there might be something more to that, but I'm not an expert in this field. Dedicated lock Object is always better, read this article if you want to find out more on the topic.
Then, while synchonizing on a lock, you have to call wait() on that same object: lock.wait(). If you synchronize on this, then you call this.wait() or just wait().
When you want to notify the waiting thread, you again have to synchronize on the lock and call notify() on that object: lock.notify(). Both the monitor in the synchronize and the object on which you call notify() have to be the exact same object you have called wait() on.
Here is a code that works:
public class Test {
public static final Object lock = new Object();
public static void main(String[] args) throws Exception {
Test t1 = new Test();
t1.m1();
}
private void m1() {
Example ex = new Example();
Thread t1 = new Thread(ex);
t1.start();
synchronized (lock) {
System.out.println("waiting");
try {
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static class Example implements Runnable {
#Override
public void run() {
System.out.println("Running");
notifyMethod();
}
private void notifyMethod() {
System.out.println("Notifying");
synchronized (lock) {
try {
Thread.sleep(1000);
} catch (Exception ex) {
ex.printStackTrace();
}
lock.notify();
}
}
}
}
I was asked at an interview to write java code which is guaranteed deadlock. I wrote a standard code which presents at every Java book, like create 2 threads and call synchronized methods at different order, sleep a little before call the 2nd.
Of course this stuff didn't satisfy the interviewers, so now I'm proceeding to figure the solution out.
I discovered a piece of code:
public class Lock implements Runnable {
static {
System.out.println("Getting ready to greet the world");
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
}
public void run() {
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
}
But I'm not sure if this code satisfied them? Sure. The code never ends execution, but is it a true deadlock? Aren't deadlocks about synchronization? And, for example, I can also write an endless cycle, put a Thread.sleep inside and name it a "deadlock".
So the question is: is it possible to write a classic deadlock using synchronized methods but 100% guaranteed? (Please don't tell me about very, very, very likely deadlock cases. I know it.)
Thanks.
Create two resources, and have each thread try to get one before releasing the other, but in different orders. For instance:
CountDownLatch a = new CountDownLatch (1);
CountDownLatch b = new CountDownLatch (1);
void one() throws InterruptedException {
a.await();
b.countDown();
}
void two() throws InterruptedException {
b.await();
a.countDown();
}
The thread that runs one can't release b, because it's waiting for a. It'll wait forever, because the thread that runs two can't release a because it's waiting for b.
One or the classic deadlock scenarios is when you acquire locks in reverse order.
class Resource1 {
synchronized static void method1() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
Resource2.method1();
}
}
class Resource2 {
synchronized static void method1() {
Resource1.method1();
}
}
public class MultiThreadApp {
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
Resource2.method1();
}
}).start();
Resource1.method1();
}
}
public class Deadlock {
public static void main(String[] args) {
String res1 = "a";
String res2 = "s";
new Thread(
() -> {
synchronized (res1) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
}
synchronized (res2) {
}
}
}
).start();
new Thread(
() -> {
synchronized (res2) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
}
synchronized (res1) {
}
}
}
).start();
}
}
I am new to java thread. I am unable to give the lock back to the thread from the main thread in the following code. I am getting the undesired output because i am unable to unlock the thread. I want thread to increment the value using thread (goes to wait state after that) and after printing the value, release the lock to print the next incremented value.
class Foo implements Runnable
{
public volatile int value=0,i=0;
Thread t=new Thread();
public void method(Thread t)
{
this.t = t;
}
#Override
public synchronized void run()
{
while(i<3)
{
value++;//receive and process ACK
i++;
try
{
System.out.println("im thread here");
wait();
System.out.println("passed wait");
}
catch(InterruptedException ex){
}
System.out.println("im notified");
}//while
//}//sync
}//run method
public int getValue()
{
try
{
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println(e);
}
return value;
}
}//class foo
public class ThreadTest
{
public static int value1,times=0;
public static void main(String[] args)
{
Foo foo=new Foo();
Thread t=new Thread(foo);
foo.method(t);
t.start();
while(times<3)
{
synchronized(t)
{
value1=foo.getValue();
times++;
System.out.println(value1);
System.out.println(t.getState());
try
{
t.notify();
System.out.println("Notify is reached");
}
catch(IllegalMonitorStateException ex)
{
System.out.println("Thread is blocked");
}
}//sync
}//while
}//main
}//mclasss
Are you trying to do something like this? If you really must use wait/notify & want to use Runnable.
I added a wait block, otherwise the main thread may finish before the background thread increments the value.
class Foo implements Runnable {
public volatile int value = 0, i = 0;
private Thread backgroundThread;
public void setThread(Thread thread) {
this.backgroundThread = thread;
}
#Override
public void run() {
synchronized (backgroundThread) {
while (i < 2) {
value++;
i++;
backgroundThread.notify();
try {
System.out.println("background thread wait start");
backgroundThread.wait();
System.out.println("background thread notified");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
public int getValue() {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
}
public class ThreadTest {
public static int value1, times = 0;
public static void main(String[] args) {
Foo foo = new Foo();
final Thread thread = new Thread(foo);
foo.setThread(thread);
thread.start();
while (times < 3) {
synchronized (thread) {
value1 = foo.getValue();
times++;
System.out.println(value1);
System.out.println(thread.getState());
thread.notify();
try {
thread.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Or you can extend thread:
class BackgroundThread extends Thread {
public volatile int value = 0, i = 0;
#Override
public synchronized void run() {
while (i < 2) {
value++;
i++;
notify();
try {
System.out.println("background thread wait start");
wait();
System.out.println("background thread notified");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
public int getValue() {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
}
public class ThreadTest {
public static int value1, times = 0;
public static void main(String[] args) {
BackgroundThread backgroundThread = new BackgroundThread();
backgroundThread.start();
while (times < 3) {
synchronized (backgroundThread) {
value1 = backgroundThread.getValue();
times++;
System.out.println(value1);
System.out.println(backgroundThread.getState());
backgroundThread.notify();
try {
backgroundThread.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
It is very unclear what you really want to do but we will assume here that you want to run a thread in the background which should run only when its spawner (let's say the main thread) allows it to.
The JDK has several tools for this already, no need to rely on the low level wait() and notify{,All}() methods.
One example of such a primitive is a CountDownLatch. It is a one-use entity which allows you to specify the times a given set of threads should countDown() it before any threads .await()ing for them can trigger.
In combination with the multithread handling classes which appeared as far back as Java 1.5, this means you could do something like this:
// Implementation of a Runnable waiting for the counter to trigger
public final class MyWaitingClass
implements Runnable
{
private final CountDownLatch latch;
public MyWaitingClass(final CountDownLatch latch)
{
this.latch = latch;
}
#Override
public void run()
{
try {
latch.await();
// do whatever is necessary
} catch (InterruptedException e) {
// Argh; interrupted before the latch was released
Thread.currentThread().interrupt();
}
}
}
// In the main class:
final ExecutorService executor = Executors.newSingleThreadPool();
final CountDownLatch latch = new CountDownLatch(1);
final Runnable runnable = new MyWaitingClass(latch);
executor.submit(runnable);
// do whatever is needed; then:
latch.countDown();
I am using the JNativeHook library.
An instance of GlobalKeyListener starts listening to Keystrokes and adds them to arrayList1; problem is that the arrayList1 does not seem to get updated (list1itemCount does never get bigger then 0) when accessing it over the infinite while(true) loop in the Child class. Why is that and what must I do to achieve that?
public class Child {
public static void main(String[] args) {
// Get the logger for "org.jnativehook" and set the level to warning.
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
GlobalKeyListener globalkeylistener = new GlobalKeyListener();
GlobalScreen.addNativeKeyListener(globalkeylistener);
Connection conn;
while(true){
int list1itemCount = globalkeylistener.arrayList1.size();
if (list1itemCount >= 4)
System.out.println(list1itemCount);
}
}
}
GlobalKeyListener Class:
public class GlobalKeyListener implements NativeKeyListener {
ArrayList<Class1> arrayList1 = new ArrayList<>();
public ArrayList<Class1> listing() {
return arrayList1;
}
public void nativeKeyPressed(NativeKeyEvent e) {
arrayList1.add(new Class1(e.getKeyCode(), 1));
}
public void nativeKeyReleased(NativeKeyEvent e) {
arrayList1.add(new Class1(e.getKeyCode(), 0));
}
public void nativeKeyTyped(NativeKeyEvent e) {
}
}
This is a multithreading issue. The keyEvent updates occur on a different thread, and your while(true) won't update. Also, the ArrayList itself is not threadsafe as you've written it.
It would be better to synchronize on something (the easiest, not necessarily best) thing is the key listener itself, and have it wait until the update occurs and then notify. Here's the modified code:
GlobalKeyListener.java
public class GlobalKeyListener implements NativeKeyListener {
ArrayList<Class1> arrayList1 = new ArrayList<>();
public ArrayList<Class1> listing() {
return arrayList1;
}
public void nativeKeyPressed(NativeKeyEvent e) {
synchronized(this) {
arrayList1.add(new Class1(e.getKeyCode(), 1));
this.notifyAll();
}
}
public void nativeKeyReleased(NativeKeyEvent e) {
synchronized(this) {
arrayList1.add(new Class1(e.getKeyCode(), 0));
this.notifyAll();
}
}
public void nativeKeyTyped(NativeKeyEvent e) {
}
}
Child.java
public class Child {
public static void main(String[] args) throws InterruptedException {
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
GlobalKeyListener globalkeylistener = new GlobalKeyListener();
GlobalScreen.addNativeKeyListener(globalkeylistener);
synchronized(globalkeylistener) {
while(true){
int list1itemCount = globalkeylistener.arrayList1.size();
if (list1itemCount >= 4) {
System.out.println(list1itemCount);
}
globalkeylistener.wait();
}
}
}
}
I'm doing a thread who tells me when an event happens. I think that thread is not necessary if event can be controlled by timer for example. But I need an event every minute. Trouble are two:
1. When event is inside a thread occurs too fast. It seems like loop over thread. But threads are necessary to listen or catch an event.
2. I can't tell method which custom object must dispatch event, and then capture this event from a new class
I hope that you can help, here is code:
import java.util.Observer;
import java.util.Observable;
public class Main {
public static void main(String[] args) {
Threading test = new Threading();
test.start();
}
}
class ResponseHandler implements Observer {
#Override
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
String resp = (String) arg;
System.out.println("\n Received response: " + resp);
}
}
}
class EventSource extends Observable implements Runnable {
#Override
public void run() {
try {
while (true) {
Object msg = new Object(); //I guess that this must have an object here, that throws a timeout
setChanged();
notifyObservers(msg);
}
} catch (Exception e) { e.printStackTrace();}
}
}
class Obj {
EventSource _eventSource;
ResponseHandler _responseHandler;
public Obj() {
try {
_eventSource = new EventSource();
_responseHandler = new ResponseHandler();
_eventSource.addObserver(_responseHandler);
} catch (Exception ex) {
System.out.print(ex);
}
}
}
class Threading extends Obj implements Runnable {
Thread _thread;
public void run() {
while (true) {
try {
_eventSource.run(); //Event which never stops
Thread.sleep(1000); //hey thread what are you doing?
} catch (InterruptedException ex) {
}
System.out.println("Thread");
}
}
//Singlethon
public void start() {
if (_thread == null) {
_thread = new Thread(this);
_thread.start();
}
}
}