Hi I have a class that is a remote object and I implemented methods.
Then I just wanted to test it in my local. So I added a main method on it.
Then in main, I called runtUtilApp method , that just executes notepad, after some sleep I finish the working of notepad and I called stop method. After the all execution I wait program to finish execution. But it is still working and not ending.
What is the reason of this ?
I am thinking wrong ?
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.*;
public class ClientImp extends UnicastRemoteObject implements Remote{
private static final long serialVersionUID = 227L;
private Process proc;
/**
* constructor
*/
public ClientImp() throws RemoteException {
super();
}
public boolean runApp() throws RemoteException {
try {
Runtime rt = Runtime.getRuntime();
proc = rt.exec("notepad");
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
public boolean stopCurrentUtilApp() throws RemoteException {
proc.destroy();
return true;
}
public static void main(String[] args) {
client;
try {
ClientImp client = new ClientImp();
client.runUtilApp();
Thread.sleep(10000);
client.stopCurrentUtilApp();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
(I know this is a old question, but as it is referenced by many other RMI related questions I want to complete / extend the answer that was already given)
As already stated, the JVM is not exiting because a non-daemon RMI thread is still executing. This thread started to execute when the constructor of UnicastRemoteObject has been executed.
This constructor itself calls the static method UnicastRemoteObject.exportObject(this, ...) which is starting the RMI thread.
To end the thread, one could either call System.exit() or unexport the Object using UnicastRemoteObject.unexportObject(everyObjectThatHasBeenExported). The later has the advantage of not shuting down the JVM.
This is usefull in case you are building a restartable server / network service.
In this case not calling unexportObject on old (no more used) objects clutters the rmi thread. Moreover, I assume the exportedObject won't get removed by garbage collection because the rmi thread is still holding a reference on it.
Because your class extends UnicastRemoteObject, which means that when you create a new instance of your class, the UnicastRemoteObject constructor is called, which exports this object as an RMI server object, which cause a non-daemon RMI thread to start.
Call System.exit() to exit from the JVM.
Related
I want to see how Jboss creates/assign different threads from Thread pool once it finds previous thread busy.For that i tried to write down a code I hope making a thread sleep will make it busy and Jboss will create a new one. But it didnt work.
I want my Test0 class to create 5 threads to execute run method of Test1 whenever it finds Test1 thread is busy in doing something.
public class Test1 extends Thread{
public Test1(){
System.out.println("T1 Constructor");
}
#Override
public void run() {
System.out.println("run from t1 "+ Thread.currentThread().getName());
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And I have Test0 class which will execute when jboss will start as follows
#Singleton
#Startup
public class Test0 {
private Test1 t1;
public Test0(){
}
#PostConstruct
public void starts(){
for (int i=0;i<5;i++){
t1=new Test1();
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Now in Test0 class I am manully creating 5 threads . How should i format the code to have Jboss create Thread from Thread pool?
Will it make any difference if i call t1.run() instead of t1.start() while running on servers? Because i know t1.run will not create a new thread but so this still holds same in case of servers as well?
If i understand your question correctly you want to know when a new thread is used from Jboss thread pool. How are you checking if JBoss has spawned a new thread? Is it you looking at the Jboss log. Jboss will start a new thread only if a new client request is sent to Jboss server while existing thread is already busy executing prev request. Fire multiple client request to Jboss server to see multiple threads processing your code at a given point of time.
I was reading AsyncTask.java and there are few places that I can't understand.
What does this code actually do? Judging by the comment it should create the handler, but I can't get how it can do this. The method getLooper() in the Handler class just returns the handler, so there is no way I can see it can initialize a new handler.
/** #hide Used to force static handler to be created. */
public static void init() {
sHandler.getLooper();
}
Why putting postResultIfNotInvoked() in the overriden done() method? How can it be not invoked? If I understand this right, first the call() method of mWorker will be called and then mTaskInvoked is guaranteed to be true.
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
//...
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask<Result>(mWorker) {
#Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
init() isn't really used in regular code.
It can be used in platform test code - calling it first makes the class loader initialize the static members on the current thread. It's useful to making sure the Handler is created on the main UI thread while tests run on a background thread for example.
Because of #hide, it's not usable in code written with SDK's stub version of android.jar.
This is there to fix a bug to make sure onCancelled() is called if cancel() is called early.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am searching on net but did not get satisfactory answers that what made Sun engineers to
disallow run method of Runnable interface for throwing an exception.
The intention behind the concept of multi-threading is to allow parallel processing of two or more tasks for which the run method is used. If the run method throws a CheckedException, in that case the calling thread has to wait in the corresponding catch block to wait for the same which defies the sole purpose of multi-threading.
For example: Consider the following HYPOTHETICAL scenario
The main thread starts another thread say Thread1 which supposedly say does throw some CheckedException. Now to catch that exception, the corresponding catch block has to be put somewhere. Lets say the main method itself has the same. Now to catch that exception (generate by the Thread1's run method), the main thread has to wait inside the catch block to let the execution of Thread1's run method complete which will not be acceptable as then there would be no use of multithreading here.
Moreover the Future and Callable tasks are based on the above hypothesis only.
The answer to the question can be a question to ask yourself that if run method throws an exception then what would catch it?
From the JCIP docs:
Runnable is a fairly limiting abstraction; run can not return a value
or throw checked exception .
However you can use Callable, and submit it to an ExecutorService and waiting for result with FutureTask.isDone() returned by the ExecutorService.submit()
Something like this:
Callable<Void> callable = new Callable<Void>() {
public Void call() {
// whatever you want
return null;
}
};
To fill that gap since Jdk 1.5 onwords Callable<V> is introduced which provides you create async task and that returns a result and may throw an exception.
Code snippet -
public class MyCallable implements Callable<String> {
#Override
public String call() throws Exception {
...
}
}
...
FutureTask<String> futureTask1 = new FutureTask<String>(new MyCallable());
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(futureTask1);
try{
String result = futureTask1.get();
...
}catch(Exception ex){ // catch that exception
}
Checked Exception vs Unchecked Exception.
The first point is a wrong assumption that run() method cannot throw an exception. See the below code compiles
public class Test extends Thread{
#Override
public void run() throws IllegalArgumentException {
// TODO Auto-generated method stub
super.run();
}
}
And now see the below code , which is won't compile.
public class Test extends Thread{
#Override
public void run() throws FileNotFoundException {
// TODO Auto-generated method stub
super.run();
}
}
The point is the run() nethod cannot throws a Checked Exception, If it can throw which Exception we would catch ??
The calling method does not call the run() directly to start a Thread. One needs to call Thread.start() which in turn calls a run() method. So there is no point in throwing an checked exception from the run() method.
Also, any exception you throw in run method will be carefully ignored by JVM. Thus, throwing it there is probably a mistake (unless you have specific exception handler for the thread)
Refer this for more explanation: Java Thread: Run method cannot throw checked exception
if any calling method(for example void m1()) throws exception called method (pp.m1()) has to either solve or rethrow the exception just follows////
public class Practice14 {
public void m1() throws Exception{
System.out.println("hello");
}
public static void main(String[] args) {
Practice14 pp=new Practice14();
try {
pp.m1();//here solving the exception
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
so because start() method in thread doesn't have capability to solve the exception run method won't allow you to throws exception
I have the next code:
Executor exe = Executors.newFixedThreadPool(20);
while (true) {
try {
exe.execute(new DispatcherThread(serverSocket.accept()));
continue;
} catch (SocketException sExcp) {
System.exit(-1);
} catch (Exception excp) {
System.exit(-1);
}
}
For each DispatcherThread I create a connection to the database (it means I have 20 connections), what I need to know is how I can close the connection to the database when the thread is stopped or it stops or finishes its flow.
You cannot directly know when the thread is stopped, the closest thing you have is Thread#isAlive method but it may return false when the run method in the thread has finished but the thread may not be stopped since the JVM cannot guarantee it. But if your DispatcherThread class implements Runnable interface then you can write the clean up at the bottom of the run method.
Skeleton code:
class DispatcherThread implements Runnable {
#Override
public void run() {
try {
//open database connection an such...
//...
//handle the work here...
} catch (...) {
//ALWAYS handle the exceptions
} finally {
//cleanup tasks like close database connection
}
}
}
By the way, Thread suffix is not a good name for a class that technically is not a thread (because it doesn't extend from Thread). Instead, give a proper name according to what should do.
You could close the thread-specific connection at the end of your run() method.
A finally block would ensure that it happened however the run() method exited.
class DispatcherThread extends Runnable {
public void run() {
...
try {
...
}
finally {
// Close the connection
}
}
How do I keep an RMI server running? It currently, just binds and object, then exits..
public class WutServer {
public static void main(String[] args) throws RemoteException {
Registry registry = LocateRegistry.createRegistry(1099);
try {
registry.bind("WutManager", new WutManager());
System.out.println("Ready..");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am simply running this class. I didn't run rmic or anything..
How do I force it to stay running?
Try this:
Remote stub = UnicastRemoteObject.exportObject(new WutManager(), 0);
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("WutManager", stub);
Note: WutManager should implement java.rmi.Remote.
Your server is being DGC'd and then GC'd, which causes it to be unexported, which eventually causes the JVM to exit if it has nothing else to do. To stop that, if you are creating the Registry via LocateRegistry.createRegistry(), keep the return value of that method in a static variable. Otherwise keep a static reference to your server object.
This is an old question, but here is a new answer.
On OSX, using latest Java 9.0.4 I find that the program exits. If I use latest Java 1.8.0.162 then it does not exit and the server remains running.
You need to make WutServer implement the interface that clients will access it by, which in turn should inherit from the marker interface Remote. You also probably want to make the WutServer class inherit from UnicastRemoteObject; while there are other ways to build the remoting support, inheriting from UnicastRemoteObject is definitely the easiest way to get something going.
Try this instead (though you should probably separate the remote interface into another file and have it be redistributed separately):
public class WutServer extends UnicastRemoteObject implements WutServer.Wut {
interface Wut extends Remote {
String wut() throws RemoteException;
}
// Because of the exception...
public WutServer() throws RemoteException {}
public String wut() { return "wut"; }
public static void main(String[] args) throws RemoteException {
LocateRegistry.createRegistry(1099).rebind("WutManager",new WutServer());
System.out.println("Ready...");
}
}
Create an object and call wait of the object at the end of the main function. That is;
public static void main(String[] args) throws RemoteException {
Registry registry = LocateRegistry.createRegistry(1099);
//your object to wait
Object lockObject=new Object();
try {
registry.bind("WutManager", new WutManager());
System.out.println("Ready..");
//here makes your rmi server non-stop
synchronized(lockObject){
lockObject.wait();
}
}catch (Exception e) {
e.printStackTrace();
}
}