1

I need to send wakeup signal to a java process from another java process. Can I do it using signals? I tried to find some stuff on internet but couldnt get. Can anyone please help.

Anup Buchke
  • 5,210
  • 5
  • 22
  • 38

3 Answers3

1

I am confused on two process in same JVM part (Two class loaders ?). Either way, easiest way is to communicate over the shared local socket or a file.

You can even look at shared memory map.

saremapadhasa
  • 106
  • 1
  • 7
1

Assuming you mean two java threads the simplest approach is probably to use javas wait/notify mechanism. You can read more about how it works in the javadoc: http://docs.oracle.com/javase/7/docs/api/

Here is a sample program that demonstrates how it works. It will print the thread id alternatively as each thread runs.

public class Main {

  public static void main(String[] args) {
    final Object notifier = new Object();                       //the notifying object
    final long endingTime = System.currentTimeMillis() + 1000;  //finish in 1 s

    Runnable printThread = new Runnable(){
      @Override
      public void run() {
        synchronized (notifier){
          while(System.currentTimeMillis() < endingTime){
            try {
              notifier.wait();
              System.out.println(Thread.currentThread().getId());
              notifier.notify();  //notifies the other thread to stop waiting
            } catch (InterruptedException e) {
              e.printStackTrace();  //uh-oh
            }
          }
        }
      }
    };

    //start two threads
    Thread t1 = new Thread(printThread);
    Thread t2 = new Thread(printThread);
    t1.start();
    t2.start();

    //notify one of the threads to print itself
    synchronized (notifier){
      notifier.notify();
    }

    //wait for the threads to finish
    try {
      t1.join();
      t2.join();
    } catch (InterruptedException e) {
      e.printStackTrace();  //uh-oh
    }
    System.out.println("done");
  }
}
0

Depends on how related the threads are. If they are related then a wait/notify setup like the one suggested in one of the answers to this previous question would do the trick.

If you have more a publish/subscribe method then I recommend Guava's EventBus as a simple way to communicate between threads.

Community
  • 1
  • 1