Wednesday, 24 August 2016

How to Stop Thread in Java?

By default, a Thread stops when execution of run() method finish either normally or due to any Exception.
It is tricky to stop the Thread execution in Java as stop() method has been deprecated from Thread Class.

To make the thread stop, we organise for the run() method to exit.

Stop using boolean State variable or flag:
It is very popular to stop a Thread using flag and it's also safe because it doesn't do anything special rather than helping run() method to finish itself.
class Runner extends Thread {
     private boolean exit = false;

     @Override
     public void run() {
           while(!exit) {
                System.out.println("Thread is running");
                try {
                     Thread.sleep(500);
                } catch (InterruptedException ex) {
                     System.out.println("Exception !!");
                }
           }
           System.out.println("Stopped !!");
     }
     public void exit(boolean bExit) {
           this.exit = bExit;
     }
}

public class ThreadStopFlag {
     public static void main (String[] args) throws InterruptedException {
           Runner runner = new Runner();
           runner.start();
           Thread.sleep(1000);
           runner.exit(true);
     }
}

Output:
Thread is running
Thread is running
Stopped !!

Stop using interrupt() method:
class Runner1 extends Thread {
     @Override
     public void run() {
           while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Thread is running");
           }
           System.out.println("Stopped !!");
     }
}

public class ThreadStopUsingInterrupt {
     public static void main (String[] args) throws InterruptedException {
           Runner1 runner = new Runner1();
           runner.start();
          
           Thread.sleep(1);
          
           runner.interrupt();
     }
}
Output:
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Stopped !!

Monday, 22 August 2016

Why is Thread.stop deprecated?

Thread.stop is being deprecated because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors was in an inconsistent state, other threads might view these objects in an inconsistent state. Such objects are said to be damaged .

Threads operating on damaged objects can behave arbitrarily, either obviously or not. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that the program might be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.

Couldn't I just catch the ThreadDeath exception and fix the damaged object?
In theory, perhaps, but it would vastly complicate the task of writing correct multithreaded code.
The task would be nearly insurmountable for two reasons:
1. A thread can throw a ThreadDeath exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail, with this in mind.
2. A thread can throw a second ThreadDeath exception while cleaning up from the first (in the catch or finally clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.

In sum, it just isn't practical.

So how can we stop a thread safely? In general:
To make the thread stop, we organize for the run() method to exit.



Thursday, 18 August 2016

Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

Input: array[] = {2, 0, 2}
Output: 2
Structure is like below
| |
|_|
Output: 2

Input: array[] = {3, 0, 1, 0, 2, 0, 4}
Structure is like below
      |
|     |
|   | |
|_|_|_|
Output: 12

Approach:
Maximum water on any bar = Min(Max height bar on left, Max height bar on right) – Height of the bar.



Brute force: Time complexity O(n^2).
Dynamic programming: Time complexity O(n).

public class WaterInWarDP {

     private static int length;

     private static int maxWaterInWarDp(int[] barsInSea) {

           /* Maximum water on a bar = Min(Max left height, Max Right height). */

           /* Get Max left array.*/
           int[] maxLeft = getMaxLeftArray(barsInSea);

           /* Get Max Right array.*/
           int[] maxRight = getMaxRightArray(barsInSea);

           int waterOnBars = 0;
           for (int i = 0; i < length; i++) {
                waterOnBars = waterOnBars + 
                  Math.min(maxRight[i],maxLeft[i])-barsInSea[i];
           }

           return waterOnBars;
     }

     private static int[] getMaxRightArray(int[] barsInSea) {
           int[] maxRight = new int[length];
           maxRight[length-1] = barsInSea[length-1];
           for (int i = length-2; i >=0; i--) {
                maxRight[i] = Math.max(barsInSea[i], maxRight[i+1]);
           }
           return maxRight;
     }

     private static int[] getMaxLeftArray(int[] barsInSea) {
           int[] maxLeft = new int[length];
           maxLeft[0] = barsInSea[0];
           for (int i = 1; i < length; i++) {
                maxLeft[i] = Math.max(barsInSea[i], maxLeft[i-1]);
           }
           return maxLeft;
     }
    
    
     public static void main(String[] args) {
           int[] barsInSea = {3,0,0,2,0,4};
           length = barsInSea.length;
           int maxWater = maxWaterInWarDp(barsInSea);
           System.out.println("Maximum water : "+ maxWater);
     }
}

Monday, 8 August 2016

Stateless protocol

No client state on the server.
A stateless protocol does not require the server to retain session information or status about each communications partner for the duration of multiple requests.

The session is stored on the client. Server does not store any state about the client session on the server side.

Stateless protocol is a communications protocol that treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of request and response.

Examples
Stateless protocols include the Internet Protocol (IP) which is the foundation for the Internet, and the Hypertext Transfer Protocol (HTTP) which is the foundation of data communication for the World Wide Web.

HTTP is a Stateless protocol, meaning that each request message can be understood in isolation. Contrast this with a traditional FTP server that conducts an interactive session with the user. During the session, a user is provided a means to be authenticated and set various variables (working directory, transfer mode), all stored on the server as part of the user's state.

Advantages:
For a service which is used by 10's of thousands of concurrent users, We should make our service stateless.

It is an overall simpler implementation and you have a single code path instead of a bunch of server side logic to maintain a bunch of session state.

The stateless design simplifies the server design because there is no need to dynamically allocate storage to deal with conversations in progress.

If a client dies in mid-transaction, no part of the system needs to be responsible for cleaning up the present state of the server.

Disadvantage:
A disadvantage of statelessness is that it may be necessary to include additional information in every request, and this extra information will need to be interpreted by the server.

Stateful protocol
In contrast, a protocol which requires keeping of the internal state on the server is known as a stateful protocol.

Wednesday, 3 August 2016

Eclipse: java.lang.UnsupportedClassVersionError: Bad version number in .class file

When JVM tries to load a class and found that class file version is not supported it throws UnSupportedClassVersionError.

It generally occurs if a higher jdk version is used to compile the source file and lower jdk version is used to run the program.

Example: If you compile your java source file in jdk1.6 and try to run it on jdk 1.5, JVM will throw "java.lang.UnsupportedClassVersionError: Bad version number in .class file".


How to fix UnSupportedClassVersionError?

· Try to compile source code of that jar with the same JDK version which we are using to run the program (if source is available).


· If you don't have source try to find the compatible version of that library.

· Increase the jre version that is used to run the program.

I faced this problem while running an application on Web application on Eclipse and Tomcat. This is because there was version difference of Eclipse and Tomcat (lower jdk version in Tomcat).

I changed jre version of Tomcat to fix this problem.


Related Posts Plugin for WordPress, Blogger...