Java – URLConnection Class

Java – URLConnection Class ”; Previous Next Java URLConnection Class java.net.URLConnection, is an abstract class whose subclasses represent the various types of URL connections. Instances of this class can be used both to read from and to write to the resource referenced by the URL. For example − If you connect to a URL whose protocol is HTTP, the URL.openConnection() method returns an HttpURLConnection object. If you connect to a URL that represents a JAR file, the URL.openConnection() method returns a JarURLConnection object, etc. Steps to make a connection to a URL Following are the steps to make a connectiion to the URL and start processing. Invoke URL.openConnection() method to get connection object. Update setup parameters and general request properties as required using connection object various setter methods. Create a connection to remote object using connect() method of connection object. Once remote object is available, access the content/headers of the remote object. URLConnection Class Declaration public abstract class URLConnection extends Object URLConnection Class Fields Sr.No. Field & Description 1 protected boolean allowUserInteraction If true, this URL is being examined in a context in which it makes sense to allow user interactions such as popping up an authentication dialog. 2 protected boolean connected If false, this connection object has not created a communications link to the specified URL. 3 protected boolean doInput This variable is set by the setDoInput method. 3 protected boolean doOutput This variable is set by the setDoOutput method. 4 protected long ifModifiedSince Some protocols support skipping the fetching of the object unless the object has been modified more recently than a certain time. 5 protected URL url The URL represents the remote object on the World Wide Web to which this connection is opened. 6 protected boolean useCaches If true, the protocol is allowed to use caching whenever it can. URLConnection Class Methods The URLConnection class has many methods for setting or determining information about the connection, including the following − Sr.No. Method & Description 1 void addRequestProperty(String key, String value) Adds a general request property specified by a key-value pair. 2 boolean getAllowUserInteraction() Returns the value of the allowUserInteraction field for this object. 3 int getConnectTimeout() Returns setting for connect timeout. 4 Object getContent() Retrieves the contents of this URL connection. 5 Object getContent(Class[] classes) Retrieves the contents of this URL connection. 6 String getContentEncoding() Returns the value of the content-encoding header field. 7 int getContentLength() Returns the value of the content-length header field. 8 long getContentLengthLong() Returns the value of the content-length header field as long. 9 String getContentType() Returns the value of the content-type header field. 10 long getDate() Returns the value of the date header field. 11 static boolean getDefaultAllowUserInteraction() Returns the default value of the allowUserInteraction field. 12 boolean getDefaultUseCaches() Returns the default value of a URLConnection”s useCaches flag. 13 static boolean getDefaultUseCaches(String protocol) Returns the default value of the useCaches flag for the given protocol. 14 boolean getDoInput() Returns the value of this URLConnection”s doInput flag. 15 boolean getDoOutput() Returns the value of this URLConnection”s doOutput flag. 16 long getExpiration() Returns the value of the expires header field. 17 static FileNameMap getFileNameMap() Loads filename map (a mimetable) from a data file. 18 String getHeaderField(int n) Returns the value for the nth header field. 19 String getHeaderField(String name) Returns the value of the named header field. 20 long getHeaderFieldDate(String name, long Default) Returns the value of the named field parsed as date. 21 int getHeaderFieldInt(String name, int Default) Returns the value of the named field parsed as a number. 22 String getHeaderFieldKey(int n) Returns the key for the nth header field. 23 long getHeaderFieldLong(String name, long Default) Returns the value of the named field parsed as a number. 24 Map<String,List<String>> getHeaderFields() Returns an unmodifiable Map of the header fields. 25 long getIfModifiedSince() Returns the value of this object”s ifModifiedSince field. 26 InputStream getInputStream() Returns an input stream that reads from this open connection. 27 int getLastModified() Returns the value of the last-modified header field. 28 OutputStream getOutputStream() Returns an output stream that writes to this connection. 29 Permission getPermission() Returns a permission object representing the permission necessary to make the connection represented by this object. 30 int getReadTimeout() Returns setting for read timeout. 0 return implies that the option is disabled (i.e., timeout of infinity). 31 Map<String,List<String>> getRequestProperties() Returns an unmodifiable Map of general request properties for this connection. 32 String getRequestProperty(String key) Returns the value of the named general request property for this connection. 33 URL getURL() Returns the value of this URLConnection”s URL field. 34 boolean getUseCaches() Returns the value of this URLConnection”s useCaches field. 35 static String guessContentTypeFromName(String fname) Tries to determine the content type of an object, based on the specified “file” component of a URL. 36 static String guessContentTypeFromStream(InputStream is) Tries to determine the type of an input stream based on the characters at the beginning of the input stream. 37 void setAllowUserInteraction(boolean allowuserinteraction) Set the value of the allowUserInteraction field of this URLConnection. 38 void setConnectTimeout(int timeout) Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection. 39 static void setContentHandlerFactory(ContentHandlerFactory fac) Sets the ContentHandlerFactory of an application. 40 static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction) Sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value. 41 void setDefaultUseCaches(boolean defaultusecaches) Sets the default value of the useCaches field to the specified value. 42 static void setDefaultUseCaches(String protocol, boolean defaultVal) Sets the default value of the useCaches field for the named protocol to the given value. 43 void setDoInput(boolean doinput) Sets the value of the doInput field for this URLConnection to the specified value. 44 void setDoOutput(boolean dooutput) Sets the value of the doOutput field for this URLConnection to the specified value. 45 static void setFileNameMap(FileNameMap map) Sets the FileNameMap. 46 void setIfModifiedSince(long ifmodifiedsince) Sets the value of the ifModifiedSince field of this URLConnection to the specified value. 47 void setReadTimeout(int timeout) Sets the read timeout to

Java – Starting a Thread

Java – Starting a Thread ”; Previous Next Starting a Thread Once a Thread object is created, you can start it by calling start() method, which executes a call to run() method. Following is a simple syntax of start() method − void start(); Syntax of Starting a Thread The following is the syntax of starting a thread – thread_obj.start(); Here, thread_obj is an object to the Thread class, and start() is the method of the Thread class. Start a Thread by Implementing Runnable Interface In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. Example package com.tutorialspoint; class RunnableDemo implements Runnable { private String threadName; RunnableDemo( String name) { threadName = name; System.out.println(“Thread: ” + threadName + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + threadName + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); } System.out.println(“Thread: ” + threadName + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) { RunnableDemo runnableDemo1 = new RunnableDemo( “Thread-1”); RunnableDemo runnableDemo2 = new RunnableDemo( “Thread-2″); Thread thread1 = new Thread(runnableDemo1); Thread thread2 = new Thread(runnableDemo2); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Start a Thread by Extending Thread Class Here is the preceding program rewritten to extend the Thread − In this example, we”ve created a ThreadDemo class which extends Thread class. We”re calling super(name) in constructor() method to assign a name to the thread and called super.start() to start the thread processing. Example package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2″); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Start a Thread (with Demonstrating sleep() method) In this example, we”re creating couple of objects of ThreadDemo class which extends Thread class. We”re calling super(name) in constructor() method to assign a name to the thread and called super.start() to start the thread processing. Using sleep() method, we”re introducing the delay in processing. Example package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2″); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Dead Print Page Previous Next Advertisements ”;

Java – Naming Thread

Java – Naming a Thread with Examples ”; Previous Next Name a Thread while Implementing a Runnable Interface If your class is intended to be executed as a thread and is implementing a Runnable interface. You will need to instantiate a Thread object using the following constructor − Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread. Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Example In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. package com.tutorialspoint; class RunnableDemo implements Runnable { private String threadName; RunnableDemo( String name) { threadName = name; System.out.println(“Thread: ” + threadName + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + threadName + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); } System.out.println(“Thread: ” + threadName + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) { RunnableDemo runnableDemo1 = new RunnableDemo( “Thread-1”); RunnableDemo runnableDemo2 = new RunnableDemo( “Thread-2″); Thread thread1 = new Thread(runnableDemo1); Thread thread2 = new Thread(runnableDemo2); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Naming a Thread while extending a Thread Class The second way to create a thread is to create a new class that extends Thread class. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. In order to name the thread, we need to call the super class Thread constructor with name. class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); … } … } Example 1 Here is the preceding program rewritten to extend the Thread − In this example, we”ve created a ThreadDemo class which extends Thread class. We”re calling super(name) in constructor() method to assign a name to the thread and called super.start() to start the thread processing. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2″); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, State: Running Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Example 2 In this example, we”ve created a ThreadDemo class which extends Thread class. We”re not passing any name to the Thread and it will print the default names assigned to the threads by the system. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); thread1.start(); thread2.start(); } } Output Thread: main, State: New Thread: main, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-0, State: Running Thread: Thread-0, 4 Thread: Thread-0, 3 Thread: Thread-1, State: Running Thread: Thread-0, 2 Thread: Thread-1, 4 Thread: Thread-0, 1 Thread: Thread-1, 3 Thread: Thread-0, State: Dead Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Print Page Previous Next Advertisements ”;

Java – Data Structures

Java – Data Structures ”; Previous Next The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes − Enumeration BitSet Vector Stack Dictionary Hashtable Properties All these classes are now legacy and Java-2 has introduced a new framework called Collections Framework, which is discussed in the next chapter − The Enumeration The Enumeration interface isn”t itself a data structure, but it is very important within the context of other data structures. The Enumeration interface defines a means to retrieve successive elements from a data structure. For example, Enumeration defines a method called nextElement that is used to get the next element in a data structure that contains multiple elements. Example Following is an example showing usage of Enumeration for a Vector. import java.util.Vector; import java.util.Enumeration; public class EnumerationTester { public static void main(String args[]) { Enumeration<String> days; Vector<String> dayNames = new Vector<>(); dayNames.add(“Sunday”); dayNames.add(“Monday”); dayNames.add(“Tuesday”); dayNames.add(“Wednesday”); dayNames.add(“Thursday”); dayNames.add(“Friday”); dayNames.add(“Saturday”); days = dayNames.elements(); while (days.hasMoreElements()) { System.out.println(days.nextElement()); } } } Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday To have more detail about this interface, check The Enumeration. The BitSet The BitSet class implements a group of bits or flags that can be set and cleared individually. This class is very useful in cases where you need to keep up with a set of Boolean values; you just assign a bit to each value and set or clear it as appropriate. Example The following program illustrates several of the methods supported by BitSet data structure − import java.util.BitSet; public class BitSetDemo { public static void main(String args[]) { BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // set some bits for(int i = 0; i < 16; i++) { if((i % 2) == 0) bits1.set(i); if((i % 5) != 0) bits2.set(i); } System.out.println(“Initial pattern in bits1: “); System.out.println(bits1); System.out.println(“nInitial pattern in bits2: “); System.out.println(bits2); // AND bits bits2.and(bits1); System.out.println(“nbits2 AND bits1: “); System.out.println(bits2); // OR bits bits2.or(bits1); System.out.println(“nbits2 OR bits1: “); System.out.println(bits2); // XOR bits bits2.xor(bits1); System.out.println(“nbits2 XOR bits1: “); System.out.println(bits2); } } Output Initial pattern in bits1: {0, 2, 4, 6, 8, 10, 12, 14} Initial pattern in bits2: {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14} bits2 AND bits1: {2, 4, 6, 8, 12, 14} bits2 OR bits1: {0, 2, 4, 6, 8, 10, 12, 14} bits2 XOR bits1: {} The Vector The Vector class is similar to a traditional Java array, except that it can grow as necessary to accommodate new elements. Like an array, elements of a Vector object can be accessed via an index into the vector. The nice thing about using the Vector class is that you don”t have to worry about setting it to a specific size upon creation; it shrinks and grows automatically when necessary. Example The following program illustrates several of the methods supported by Vector collection − import java.util.*; public class VectorDemo { public static void main(String args[]) { // initial size is 3, increment is 2 Vector v = new Vector(3, 2); System.out.println(“Initial size: ” + v.size()); System.out.println(“Initial capacity: ” + v.capacity()); v.addElement(new Integer(1)); v.addElement(new Integer(2)); v.addElement(new Integer(3)); v.addElement(new Integer(4)); System.out.println(“Capacity after four additions: ” + v.capacity()); v.addElement(new Double(5.45)); System.out.println(“Current capacity: ” + v.capacity()); v.addElement(new Double(6.08)); v.addElement(new Integer(7)); System.out.println(“Current capacity: ” + v.capacity()); v.addElement(new Float(9.4)); v.addElement(new Integer(10)); System.out.println(“Current capacity: ” + v.capacity()); v.addElement(new Integer(11)); v.addElement(new Integer(12)); System.out.println(“First element: ” + (Integer)v.firstElement()); System.out.println(“Last element: ” + (Integer)v.lastElement()); if(v.contains(new Integer(3))) System.out.println(“Vector contains 3.”); // enumerate the elements in the vector. Enumeration vEnum = v.elements(); System.out.println(“nElements in vector:”); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + ” “); System.out.println(); } } Output Initial size: 0 Initial capacity: 3 Capacity after four additions: 5 Current capacity: 5 Current capacity: 7 Current capacity: 9 First element: 1 Last element: 12 Vector contains 3. Elements in vector: 1 2 3 4 5.45 6.08 7 9.4 10 11 12 The Stack The Stack class implements a last-in-first-out (LIFO) stack of elements. You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top of the others. When you pull an element off the stack, it comes off the top. In other words, the last element you added to the stack is the first one to come back off. Example The following program illustrates several of the methods supported by Stack collection − import java.util.*; public class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println(“push(” + a + “)”); System.out.println(“stack: ” + st); } static void showpop(Stack st) { System.out.print(“pop -> “); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println(“stack: ” + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println(“stack: ” + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println(“empty stack”); } } } Output stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99) stack: [42, 66, 99] pop -> 99 stack: [42, 66] pop -> 66 stack: [42] pop -> 42 stack: [ ] pop -> empty stack The Dictionary The Dictionary class is an abstract class that defines a data structure for mapping keys to values. This is useful in cases where you want to be able to access data via a particular key rather than an integer index. Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure rather than a specific implementation. Example The following example shows the usage of Java Dictionary keys() method. We”re creating a dictionary instance using Hashtable object of Integer, Integer. Then we”ve added few elements to it. An enumeration is retrieved using keys() method and enumeration is then iterated to print the keys of the dictionary. package com.tutorialspoint; import java.util.Enumeration; import java.util.Dictionary; import java.util.Hashtable; public class DictionaryDemo { public static void main(String[] args) { // create a new hashtable Dictionary<Integer, Integer> dictionary = new Hashtable<>();

Java – Nested try Block

Java – Nested Try Block ”; Previous Next Nested Try Block A try block can be nested within another try block. This structure is termed as Nested try block. Whenever an exception is raised within a nested try block, its exception is pushed to Stack. The exception propagates from child to parent try block and so on. Syntax The syntax for nested catch blocks looks like the following − try { // parent try block try { // child try block } catch(ExceptionType1 e1){ // child catch block } } catch (ExceptionType2 e1) { // parent catch block } The previous statements demonstrate two try/catch blocks, but you can have any number of them. If an exception occurs in the protected child code, the exception is thrown to the catch block of the child list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes up to the parent catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. Pointer To Remember While Using Nested Try Block Child catch block should have specific exception for better code clarity. Parent catch block can have more generic exception handled so that if child catch block is not able to handle the exception then parent catch block can handle it. There in no restriction on exception hiearchy to be used in child vs parent catch block. If a exception is handled correctly in child catch block, then in parent, another exception can be raised and handled. Java Nested Try Block Example Here is code segment showing how to use nested try/catch statements. In this example, we”re creating an error by dividing a value by 0 in a nested try block. The child catch block is handling the exception and printing the same. Now in parent try block, we”re again creating an error by using an invalid array index while accessing array elements and exception is raised. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; try { int b = 0; int c = 1/b; }catch(Exception e) { System.out.println(“Exception thrown: ” + e); } System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown: ” + e); } System.out.println(“Out of the block”); } } Output Exception thrown: java.lang.ArithmeticException: / by zero Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block More Examples Example 1 In this code segment, we”re showing how to use another example of nested try/catch statements. In this example, we”re creating an error by dividing a value by 0 in nested try block but we”re not handling in corresponding catch block. As parent try block is handling the exception raised as generic exception, it captures the exception raised by child catch block and prints the same. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; try { int b = 0; int c = 1/b; }catch(ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown: ” + e); } System.out.println(“Access element three :” + a[3]); } catch (Exception e) { System.out.println(“Exception thrown: ” + e); } System.out.println(“Out of the block”); } } Output Exception thrown: java.lang.ArithmeticException: / by zero Out of the block Example 2 In this code segment, we”re showing the case of nested try/catch statements where exceptions are not handled by any of the catch block. In this example, we”re creating an error by dividing a value by 0 in nested try block but we”re not handling this kind of exception in any catch block. Now JVM will capture the exception and terminate the program without printing the last statement. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; try { int b = 0; int c = 1/b; }catch(ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown: ” + e); } System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown: ” + e); } System.out.println(“Out of the block”); } } Output Exception in thread “main” java.lang.ArithmeticException: / by zero at com.tutorialspoint.ExcepTest.main(ExcepTest.java:10) Print Page Previous Next Advertisements ”;

Java – Socket Class

Java – Socket Class with Examples ”; Previous Next Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket. The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them. After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client”s OutputStream is connected to the server”s InputStream, and the client”s InputStream is connected to the server”s OutputStream. The Java Socket class represents the socket that both the client and the server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method. Declaration public class Socket extends Object implements Closeable Constructors Sr.No. Method & Description 1 public Socket() This method creates an unconnected socket, with the system-default type of SocketImpl. 2 public Socket(String host, int port) throws UnknownHostException, IOException This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server. 3 public Socket(String host,int port,InetAddress localAddr,int localPort) throws IOException This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied. 4 public Socket(InetAddress host, int port) throws IOException This method is identical to the previous constructor, except that the host is denoted by an InetAddress object. 5 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException. This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String. 6 public Socket(Proxy proxy) This method creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of any other settings. When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port. Methods Some methods of interest in the Socket class are listed here. Notice that both the client and the server have a Socket object, so these methods can be invoked by both the client and the server. Sr.No. Method & Description 1 void bind(SocketAddress bindpoint) Binds the socket to a local address. 2 void close() Closes this socket. 3 void connect(SocketAddress endpoint) Connects this socket to the server. 4 void connect(SocketAddress endpoint, int timeout) Connects this socket to the server with a specified timeout value. 5 SocketChannel getChannel() Returns the unique SocketChannel object associated with this socket, if any. 6 InetAddress getInetAddress() Returns the address to which the socket is connected. 7 InputStream getInputStream() Returns an input stream for this socket. 8 boolean getKeepAlive() Tests if SO_KEEPALIVE is enabled. 9 InetAddress getLocalAddress() Gets the local address to which the socket is bound. 10 int getLocalPort() Returns the local port number to which this socket is bound. 11 SocketAddress getLocalSocketAddress() Returns the address of the endpoint this socket is bound to. 12 boolean getOOBInline() Tests if SO_OOBINLINE is enabled. 13 <T> T getOption(SocketOption<T> name) Returns the value of a socket option. 14 OutputStream getOutputStream() Returns an output stream for this socket. 15 int getPort() Returns the remote port number to which this socket is connected. 16 int getReceiveBufferSize() Gets the value of the SO_RCVBUF option for this Socket, that is the buffer size used by the platform for input on this Socket. 17 SocketAddress getRemoteSocketAddress() Returns the address of the endpoint this socket is connected to, or null if it is unconnected. 18 boolean getReuseAddress() Tests if SO_REUSEADDR is enabled. 19 int getSendBufferSize() Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform for output on this Socket. 20 int getSoLinger() Returns setting for SO_LINGER. 21 int getSoTimeout() Returns setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity). 22 boolean getTcpNoDelay() Tests if TCP_NODELAY is enabled. 23 int getTrafficClass() Gets traffic class or type-of-service in the IP header for packets sent from this Socket 24 boolean isBound() Returns the binding state of the socket. 25 boolean isClosed() Returns the closed state of the socket. 26 boolean isConnected() Returns the connection state of the socket. 27 boolean isInputShutdown() Returns whether the read-half of the socket connection is closed. 28 boolean isOutputShutdown() Returns whether the write-half of the socket connection is closed. 29 void sendUrgentData(int data) Send one byte of urgent data on the socket. 30 void setKeepAlive(boolean on) Enable/disable SO_KEEPALIVE. 31 void setOOBInline(boolean on) Enable/disable SO_OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded. 32 <T> Socket setOption(SocketOption<T> name, T value) Sets the value of a socket option. 33 void setPerformancePreferences(int connectionTime, int latency, int bandwidth) Sets performance preferences for this socket. 34 void setReceiveBufferSize(int size) Sets the SO_RCVBUF option to the specified value for this Socket. 35 void setReuseAddress(boolean on) Enable/disable the SO_REUSEADDR socket option. 36 void setSendBufferSize(int size) Sets the SO_SNDBUF option to the specified value for this Socket. 37 static void setSocketImplFactory(SocketImplFactory fac) Sets the client socket implementation factory for the application. 38 void setSoLinger(boolean on, int linger) Enable/disable SO_LINGER with the specified linger time in seconds. 39 void setSoTimeout(int timeout) Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. 40 void setTcpNoDelay(boolean on) Enable/disable TCP_NODELAY (disable/enable Nagle”s algorithm). 41 void setTrafficClass(int tc) Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket. 42 void shutdownInput() Places the input stream

Java – Iterators

Java – How to Use Iterator? ”; Previous Next Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface. Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. In general, to use an iterator to cycle through the contents of a collection, follow these steps − Obtain an iterator to the start of the collection by calling the collection”s iterator( ) method. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. Within the loop, obtain each element by calling next( ). For collections that implement List, you can also obtain an iterator by calling ListIterator. The Methods Declared by Iterator Sr.No. Method & Description 1 boolean hasNext( ) Returns true if there are more elements. Otherwise, returns false. 2 Object next( ) Returns the next element. Throws NoSuchElementException if there is not a next element. 3 void remove( ) Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ). The Methods Declared by ListIterator Sr.No. Method & Description 1 void add(Object obj) Inserts obj into the list in front of the element that will be returned by the next call to next( ). 2 boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false. 3 boolean hasPrevious( ) Returns true if there is a previous element. Otherwise, returns false. 4 Object next( ) Returns the next element. A NoSuchElementException is thrown if there is not a next element. 5 int nextIndex( ) Returns the index of the next element. If there is not a next element, returns the size of the list. 6 Object previous( ) Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. 7 int previousIndex( ) Returns the index of the previous element. If there is not a previous element, returns -1. 8 void remove( ) Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked. 9 void set(Object obj) Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ). Example 1 Here is an example demonstrating Iterator. It uses an ArrayList object, but the general principles apply to any type of collection. import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IteratorDemo { public static void main(String args[]) { // Create an array list List<String> al = new ArrayList<>(); // add elements to the array list al.add(“C”); al.add(“A”); al.add(“E”); al.add(“B”); al.add(“D”); al.add(“F”); // Use iterator to display contents of al System.out.print(“Original contents of al: “); Iterator<String> itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + ” “); } System.out.println(); } } Output Original contents of al: C A E B D F Example 2 Here is an example demonstrating ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection. Of course, ListIterator is available only to those collections that implement the List interface. import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IteratorDemo { public static void main(String args[]) { // Create an array list List<String> al = new ArrayList<>(); // add elements to the array list al.add(“C”); al.add(“A”); al.add(“E”); al.add(“B”); al.add(“D”); al.add(“F”); // Use iterator to display contents of al System.out.print(“Original contents of al: “); Iterator<String> itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + ” “); } } } Output Original contents of al: C A E B D F Example 3 Here is an example demonstrating ListIterator to modify the list while iterating. It uses an ArrayList object, but the general principles apply to any type of collection. import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IteratorDemo { public static void main(String args[]) { // Create an array list List<String> al = new ArrayList<>(); // add elements to the array list al.add(“C”); al.add(“A”); al.add(“E”); al.add(“B”); al.add(“D”); al.add(“F”); // Use iterator to display contents of al System.out.print(“Original contents of al: “); Iterator<String> itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + ” “); } System.out.println(); // Modify objects being iterated ListIterator<String> litr = al.listIterator(); while(litr.hasNext()) { Object element = litr.next(); litr.set(element + “+”); } System.out.print(“Modified contents of al: “); itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + ” “); } System.out.println(); // Now, display the list backwards System.out.print(“Modified list backwards: “); while(litr.hasPrevious()) { Object element = litr.previous(); System.out.print(element + ” “); } System.out.println(); } } Output Original contents of al: C A E B D F Modified contents of al: C+ A+ E+ B+ D+ F+ Modified list backwards: F+ D+ B+ E+ A+ C+ Print Page Previous Next Advertisements ”;

Java – Creating a Thread

Java – Creating a Thread ”; Previous Next There are two different ways to create a thread in Java. We have listed them as follows: By Implementing a Runnable Interface By Extending a Thread Class Create a Thread by Implementing a Runnable Interface If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps − Step 1 As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) Step 2 As a second step, you will instantiate a Thread object using the following constructor − Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread. Step 3 Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Example to Create a Thread by Implementing a Runnable Interface In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. package com.tutorialspoint; class RunnableDemo implements Runnable { private String threadName; RunnableDemo( String name) { threadName = name; System.out.println(“Thread: ” + threadName + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + threadName + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); } System.out.println(“Thread: ” + threadName + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) { RunnableDemo runnableDemo1 = new RunnableDemo( “Thread-1”); RunnableDemo runnableDemo2 = new RunnableDemo( “Thread-2″); Thread thread1 = new Thread(runnableDemo1); Thread thread2 = new Thread(runnableDemo2); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Create a Thread by Extending a Thread Class The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. Step 1 You will need to override run() method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method − public void run( ) Step 2 Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start( ); Example to Create a Thread by Extending a Thread Class Here is the preceding program rewritten to extend the Thread − In this example, we”ve created a ThreadDemo class which extends Thread class. We”re calling super(name) in constructor() method to assign a name to the thread and called super.start() to start the thread processing. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2″); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, State: Running Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Example: Demonstrating sleep() Method In this example, we”re show-casing use of sleep() method to delay the processing. It helps in show the parallel processing in the output. We”ve added Thread.sleep() call in the run method. InterruptedException is handled as thread can be interrupted during sleep mode. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2”); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-1, 1 Thread:

Java – Reentrant Monitor

Java – Reentrant Monitor ”; Previous Next Reentrant Monitor in Java ReetrantLock is a class that implements Lock Interface. It provides the synchronization feature with great flexibility which is why it is the most used lock class in Java. It is necessary for the reliable and fair working of thread. Here, threads are small sub-processes of a big operation. In this article, we are going to learn ReetrantLock and how they manage threads so that they can work efficiently. Working of ReetrantLock When multiple threads try to access a shared resource then, ReetrantLock restricts access to a single thread at a time through lock() and unlock() methods. Suppose there are three people trying to book a train ticket. At the same time, all three people will try to access the booking system, it may happen that two people end up booking the same seat. Reetrant Lock can handle this situation. First, all three people will request to acquire the booking system through tryLock() method. When one acquires the booking system then, it restricts the particular seat booking through lock() method. After booking, the person will call the unlock() method to release the acquired lock. Till the resources are busy other people will wait in a queue for their turn and after the release of lock they will come in a runnable state. ReetrantLock tries to provide locks in a fair manner. We can set for how long a thread can acquire lock and also, it ensures that a thread with the longest wait time may get access to lock first. By default the locks are unfair, to make it fair we need to pass Boolean value true in its constructor. Syntax ReentrantLock nameOflock = new ReentrantLock(); // by default false Or, ReentrantLock nameOflock = new ReentrantLock(true); // we can make it true The locks are explicit and can lock or unlock in any order. A single thread can ask for the lock multiple times that”s the reason the name of lock is Reentrant. We can count the number of times a lock is acquired by using getHoldCount() method. Multithreading Without Reentrant Lock The following example illustrates the multithreading witout use of Reetrant Lock in above code. We”ve created a class Thrd with a method operation() to perform a given task. Now we”ve created three thread classes and call the operation() method. In the main() method, three objects of thread class are defined and their start() method to start the execution of threads. Example of Multithreading Without Reentrant Lock package com.tutorialspoint; class Thrd { static void operation(int data) { for(int i = 1; i <= 4; i++) { System.out.println(data++); } } } class Thrd1 extends Thread { // thread number 1 public void run() { Thrd.operation(1); // method calling } } class Thrd2 extends Thread { // thread number 2 public void run() { Thrd.operation(5); // method calling } } class Thrd3 extends Thread { // thread number 3 public void run() { Thrd.operation(10); // method calling } } public class TestThread { public static void main(String args[]) { // creating object for thread class Thrd1 oprt1 = new Thrd1(); Thrd2 oprt2 = new Thrd2(); Thrd3 oprt3 = new Thrd3(); // Starting the thread operation oprt1.start(); oprt2.start(); oprt3.start(); } } This produces a different result every time you run this program − Output 1 2 3 4 10 11 12 13 5 6 7 8 Multithreading With Reentrant Lock The following example illustrates the use of Reetrant Lock in above code. We”ve created a class Thrd and inside this thread, we”ve defined an object of ReentrantLock. A method operation() store the Boolean value of tryLock() method to a variable named lockAcquired which will check if lock gets acquired by any thread or not. If the lock is acquired lock is given to that thread using lock() method and then the thread start performing the given task. The task will be performed in the try block and the lock will be released in the finally block using unlock() method. Now we”ve created three thread classes and call the operation() method. In the main() method, three objects of thread class are defined and their start() method to start the execution of threads. Example of Multithreading With Reentrant Lock package com.tutorialspoint; import java.util.concurrent.locks.ReentrantLock; class Thrd { // creating object of ReentrantLock class private static ReentrantLock lockr = new ReentrantLock(); static void operation(int data) { // give access to lock boolean lockAcquired = lockr.tryLock(); if (lockAcquired) { try { lockr.lock(); // giving lock to thread for(int i = 1; i <= 4; i++) { System.out.println(data++); } // checking lock count System.out.println(“Count of Lock: ” + lockr.getHoldCount()); } finally { lockr.unlock(); // unlocking the lock } } else { System.out.println(“I am in else block”); } } } class Thrd1 extends Thread { // thread number 1 public void run() { Thrd.operation(1); // method calling } } class Thrd2 extends Thread { // thread number 2 public void run() { Thrd.operation(5); // method calling } } class Thrd3 extends Thread { // thread number 3 public void run() { Thrd.operation(10); // method calling } } public class TestThread { public static void main(String args[]) { // creating object for thread class Thrd1 oprt1 = new Thrd1(); Thrd2 oprt2 = new Thrd2(); Thrd3 oprt3 = new Thrd3(); // Starting the thread operation oprt1.start(); oprt2.start(); oprt3.start(); } } This produces a different result every time you run this program − Output I am in else block 5 6 7 8 Count of Lock: 2 I am in else block Multithreading With Reentrant Lock as True The following example illustrates the use of Reetrant Lock in above code. We”ve created a class Thrd and inside this thread, we”ve defined an object of ReentrantLock with fair value as true. A method operation() store the Boolean value of tryLock() method to a variable named lockAcquired which will check if lock gets acquired by any thread or not. If the lock is acquired lock is given to that thread

Java – Thread Deadlock

Java – Thread Deadlock ”; Previous Next Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object. Here is an example. Example: Demonstrating Deadlock Situation public class TestThread { public static Object Lock1 = new Object(); public static Object Lock2 = new Object(); public static void main(String args[]) { ThreadDemo1 T1 = new ThreadDemo1(); ThreadDemo2 T2 = new ThreadDemo2(); T1.start(); T2.start(); } private static class ThreadDemo1 extends Thread { public void run() { synchronized (Lock1) { System.out.println(“Thread 1: Holding lock 1…”); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println(“Thread 1: Waiting for lock 2…”); synchronized (Lock2) { System.out.println(“Thread 1: Holding lock 1 & 2…”); } } } } private static class ThreadDemo2 extends Thread { public void run() { synchronized (Lock2) { System.out.println(“Thread 2: Holding lock 2…”); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println(“Thread 2: Waiting for lock 1…”); synchronized (Lock1) { System.out.println(“Thread 2: Holding lock 1 & 2…”); } } } } } When you compile and execute the above program, you find a deadlock situation and following is the output produced by the program − Output Thread 1: Holding lock 1… Thread 2: Holding lock 2… Thread 1: Waiting for lock 2… Thread 2: Waiting for lock 1… The above program will hang forever because neither of the threads in position to proceed and waiting for each other to release the lock, so you can come out of the program by pressing CTRL&plus;C. Deadlock Solution Example Let”s change the order of the lock and run of the same program to see if both the threads still wait for each other − Example public class TestThread { public static Object Lock1 = new Object(); public static Object Lock2 = new Object(); public static void main(String args[]) { ThreadDemo1 T1 = new ThreadDemo1(); ThreadDemo2 T2 = new ThreadDemo2(); T1.start(); T2.start(); } private static class ThreadDemo1 extends Thread { public void run() { synchronized (Lock1) { System.out.println(“Thread 1: Holding lock 1…”); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println(“Thread 1: Waiting for lock 2…”); synchronized (Lock2) { System.out.println(“Thread 1: Holding lock 1 & 2…”); } } } } private static class ThreadDemo2 extends Thread { public void run() { synchronized (Lock1) { System.out.println(“Thread 2: Holding lock 1…”); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println(“Thread 2: Waiting for lock 2…”); synchronized (Lock2) { System.out.println(“Thread 2: Holding lock 1 & 2…”); } } } } } So just changing the order of the locks prevent the program in going into a deadlock situation and completes with the following result − Output Thread 1: Holding lock 1… Thread 1: Waiting for lock 2… Thread 1: Holding lock 1 & 2… Thread 2: Holding lock 1… Thread 2: Waiting for lock 2… Thread 2: Holding lock 1 & 2… The above example is to just make the concept clear, however, it is a complex concept and you should deep dive into it before you develop your applications to deal with deadlock situations. java_multithreading.htm Print Page Previous Next Advertisements ”;