Run thrift in new thread cant catch the exception - java

I run thrift in a thread like this:
public static void start() {
Runnable simple = new Runnable() {
public void run() {
TProcessor tprocessor = new MessageForwardsService.Processor<MessageForwardsService.Iface>(new MessageForwardsRpcInterface());
try {
simple(tprocessor);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread t = new Thread(simple);
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Thread uncaughtExceptionHandler catch a Exception**************************************************><><><><><><><><><<><><><><><");
System.out.println(e.getMessage());
e.printStackTrace();
}
});
t.start();
}
#SuppressWarnings("rawtypes")
public static void simple(MessageForwardsService.Processor processor) {
try {
TServerTransport serverTransport = new TServerSocket(WhrPublicConstants.RPC_PORT,2000);
TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
System.out.println("Starting the rpc server... on port:"+WhrPublicConstants.RPC_PORT);
server.serve();
} catch (Exception e) {
e.printStackTrace();
}
}
The rpc method is:
#Override
public int emulateDevice( String msg) throws TException {
throw new RuntimeException("just test throw exception");
return 0;
}
In the client side,I can get the error:
org.apache.thrift.transport.TTransportException
But in the thrift server side, I can't catch the exception as above.
Who can help me? Thanks.

Related

How to make main thread wait to complete UncaughtExceptionHandler execution

I have the following mutlithreaded code. I want the LatchCode.doStuff() to wait until UncaughtExceptionHandler handler completes it work, but it wasn't. How could I make the main thread to wait for it. I need to propagate the exception to parent for some project requirement to log the error into DB (should happen at the end of processing). Following is the piece of code.
public class LatchExceptionTest {
public static void main(String[] args) {
LatchCode l = new LatchCode();
Cont c = new Cont();
try {
l.doStuff(c);
System.out.println("Main Thread - work completed");
if(!c.err.isEmpty())
throw new Exception(c.err.toString());
} catch (Exception e) {
System.out.println("trace printing start");
System.out.println(c.err.toString()); // log errors to DB
System.out.println("trace printing edn");
}
}
}
class LatchCode {
public void doStuff(final Cont cont) throws RuntimeException, InterruptedException {
System.out.println("Intermediate class start");
try {
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread th, Throwable ex) {
cont.err.add(ex.getMessage());
}
};
Thread aggregatorThread = new Thread(() -> {
try {
if(cont.err.size() > 0)
return;
System.out.println("AGGREGATOR thread START");
Thread.sleep(3000);
System.out.println("AGGREGATOR thread END");
} catch (Exception e) {
throw new RuntimeException(e);
}
});
CyclicBarrier barrier = new CyclicBarrier(2, aggregatorThread);
AA a = new AA();
BB b = new BB();
CountDownLatch latch = new CountDownLatch(2);
Thread one = new Thread(() -> {
try {
a.doSomething();
} catch (Exception e) {
System.out.println("Exception in 1");
//Thread.currentThread().interrupt();
throw new RuntimeException(e.toString());
} finally {
try {
barrier.await();
} catch (Exception e) {
System.out.println("Exception in 1 finallt");
throw new RuntimeException(e.toString());
} finally {
latch.countDown();
}
}
});
Thread two = new Thread(() -> {
try {
b.doSomething();
} catch (Exception e) {
System.out.println("Exception in 2");
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
try {
barrier.await();
} catch (Exception e) {
System.out.println("Exception in 2 finallt");
throw new RuntimeException(e);
} finally {
latch.countDown();
}
}
});
one.start();
two.start();
one.setUncaughtExceptionHandler(h);
two.setUncaughtExceptionHandler(h);
latch.await();
} catch (Exception e) {
System.out.println("Exception in caller");
throw new RuntimeException(e);
} finally {
System.out.println("Intermediate class end");
}
}
}
class AA {
public void doSomething() throws Exception {
try {
System.out.println("1 start");
Thread.sleep(1);
throw new Exception("In AA");
} catch (Exception e) {
System.out.println("Exception in AA");
throw new Exception(e.toString());
}
}
}
class BB {
public void doSomething() throws Exception {
try {
System.out.println("2 start");
Thread.sleep(1);
} catch (Exception e) {
System.out.println("Exception in BB");
}
System.out.println("2 end");
}
}
class Cont {
ConcurrentLinkedQueue<String> err = new ConcurrentLinkedQueue<String>();
}
If AA.doStuff() and BB.doStuff() has loger sleeps, then I could Cont.err is not empty and getting into catch block. But whne sleep time is negligible like 1 ms, then if block in main() failed and program is executing as if there is no exception.
So I need calling thread to wait for UncaughtExceptionHandler completion. Could some one help on this.
Thanks in advance
After making exhaustive search, found the following page. Go through the details on how things work in UEH.
https://bugs.openjdk.java.net/browse/JDK-8153487
Excerpt from the above thread for short answer:
There is no guarantee that UncaughtExceptionHandlers have run before awaitTermination returns.
It is a pool thread that sets the state to TERMINATED, so it cannot wait for all pool threads to terminate!
It seems unlikely we can make this better. It seems that relying on the UEH in this way is a poor design

getting this error :-org.hibernate.LazyInitializationException: could not initialize proxy - no Session while calling it from inside the thread

public void getReportWidget(){
new Thread(new Runnable() {
public void run() {
try {
getCreatorName(users);
} catch (BusinessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
public void getCreatorName(Users userObject) {
try {
Hibernate.initialize(userObject.getCreator());
String creator = reportWidget.getCreator();
}
catch (Exception e) {
logger.error("error");
}
}
getting this error :-org.hibernate.LazyInitializationException: could not initialize proxy - no Session
You have to add
lazy=false
in hibernate configuration file.
This is works

Java thread exit without warning

my java thread exit with any warning. I have no idea why the thread exit. I can't find it in jstack. And it seems the log code hadn't run. My code below:
private class WorkThread extends Thread {
public WorkThread() {
super("work-thread");
setDaemon(false);
}
#Override
public void run() {
logger.info("start running thread work-tracker");
try {
while (!interrupted()) {
try {
// do something
} catch (Throwable e) {
logger.error("ignore all exception", e);
}
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} finally {
logger.error("work thread exit interrupted status: {}", interrupted());
}
}
}
I cannot find the log "work thread exit interrupted status" and anything about "work-thread" in the jstack log. any suggestion?
private class WorkThread extends Thread {
public WorkThread() {
super("work-thread");
setDaemon(false);
}
#Override
public void run() {
logger.error("start running thread work-tracker");
try {
while (!interrupted()) {
try {
// do something
} catch (Throwable e) {
logger.error("ignore all exception");
}
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
}
Thread.currentThread().interrupt();
}
} finally {
logger.error("work thread exit interrupted status: {}" +interrupted());
}
}
}

Threaded Server stuck on accept() AKA How to shutdown a MulThreaded Server via client input?

Since I am stuck for this for a week now and still haven't firgured it out I try to express what I want as cleary as possible.
I have a Server which can handle Multiple Clients and communicates with them.
Whenever a client connects, the server passes the Client's request to my class RequestHandler, in which the clients commands are being processed.
If one of the clients says "SHUTDOWN", the server is supposed to cut them loose and shut down.
It doesn't work.
If only one client connects to the server, the server seems to be stuck in the accept() call and I do not know how to fix this.
THERE is already one response, but please do not take note of it, it was on a different topic which is outdated
I have two approaches and both don't seem to work.
1)If the client writes "SHUTDOWN", the shutdownFlag is set to true (in hope to exit the while loop)
2)If the client writes "SHUTDOWN", the static method shutdown() is called on the Server, which should shut him down
Below you see the implementation of my Server class, the other two classes involved are Client(all he does is connect to the Socket) and RequestHandler (this class processes the Input and writes it) .
I am 98% sure the problem lies within the Server class.
Below this is an even shorter version of the Server with just the methods without any Console outputs which might help understanding it in case you want to copy the code
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
System.out.println("Waiting for clients");
while (!shutdownFlag) {
System.out.println("shutdown flag ist : " + shutdownFlag);
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
System.out.println("Hallo");
}
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
serverSocket.close();
}
System.out.println("shutting down");
} catch (IOException e) {
System.out
.println("Exception caught when trying to listen on port "
+ PORTNUMBER + " or listening for a connection");
System.out.println(e.getMessage());
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown(){
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
while (!shutdownFlag) {
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
}
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
serverSocket.close();
}
} catch (IOException e) {
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown() {
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If you move the code in main into an instance method on Server (we'll say run here) you can just do new Server().run() inside main. That way you have an instance (this) to work with inside your run method.
Something like this:
class Server {
private boolean shutdownFlag = false; // This can't be static anymore.
public static final Server SERVER = new Server();
public static void main(String[] args) {
SERVER.run();
}
private void run() {
// Here goes everything that used to be inside main...
// Now you have the Server.SERVER instance to use outside the class
// to shut things down or whatever ...
}
}
This pattern isn't actually that great but better would be too long for here. Hopefully this gets you off to a good start.

Java socket setSoTimeout and performance hit

I'd like to gracefully close the serversocket. I have so far this code:
#Override
public void init() throws IOException {
listener = new ServerSocket();
listener.setSoTimeout(1);
listener.setReuseAddress(true);
listener.bind(new InetSocketAddress(85));
clientProcessingPool = Executors.newFixedThreadPool(50);
while (!clientProcessingPool.isShutdown()) {
try {
Socket socket = listener.accept();
clientProcessingPool.submit(new StlExecutor(socket, this));
} catch (SocketTimeoutException e) {
} catch (Exception e) {
logger.error("", e);
e.printStackTrace();
}
}
listener.close();
}
public void stop() throws Exception {
clientProcessingPool.shutdownNow();
}
Is it reasonable to set so low SO_TIMEOUT? What is reasonable value then? What is the performance hit?

Categories