• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Core Java

Java Buzzwords

July 31, 2017 By j2eereference Leave a Comment

Java is a high-level language which is identified by the 12 buzzwords:

1.   Simple

  • Java is plain and simple for those with fundamental knowledge of Object Oriented Programming.
  • Java comprises number of easily described methods for accomplishing a given task.

2. Object Oriented

  • Java is a proper object oriented language as every code and information are contained inside objects and classes.
  • The object representation in Java is trouble-free and simple to expand.
  • Java has a collection of classes that are utilized in programming by inheritance.

3.      Distributed

  • Java works in a distributed atmosphere on internet.
  • Java applications have the ability to handle distant objects on internet effortlessly.
  • Java allows several programmers at several distant locations to team up and work on same project.

4.      Compiled and Interpreted

  • Java supports both compiled and interpreted mode and hence it is a 2 stage system.
  • Java permits formation of a cross platform programming by compiling into Java Bytecode (platform independent code).
  • Java then interprets Bytecode. Bytecode produces codes that can be openly processed by the Java virtual machine.

5.      Robust

  • Java comprises several features that enable the program to be processed easily in various environments.
  • The codes are verified in Java both at compile and runtime.
  • Java supports garbage-collection thus managing memory problems.
  • Java supports exception handling thus eliminating danger of system crashing.

6.      Secured

  • Java is secured as it offers a firewall in between the application and the computer.
  • Java supports safe downloading with no threat of virus or malicious target.
  • Java attains this safety by restricting a program to the java execution atmosphere.

7.      Architecture Neutral

  • Java is void of implementation based characteristics.
  • Any modifications and updates in OS or system sources will not compel any modifications in Java Programs.

8.      Portable

  • Java enables portable codes generation. It offers a method for downloading programs effectively to every platform linked to internet.

9.      High Performance

  • The Bytecode enables elevated performance in Java.

10.  Multithreaded

  • Java programs handle several tasks by the concept of multi-threads.
  • The advantage is multithreading requires a common memory area.

11 . Dynamic

  • Java is dynamic as it has the ability to link fresh class libraries, objects and also native methods.

12. Platform Independent

  • Java platform is software based.
  • The Java Bytecode can be processed on numerous platforms like windows, Mac/OS etc.

Related Posts

  • What is exchanger in concurrency?
  • UncaughtExceptionHandler in java
  • How to generate and resolve OutOfMemoryError?
  • Difference between Spring’s Singleton scope & Singleton Design pattern
  • How to stop a thread?
  • Interrupting a thread in java
  • What is ThreadLocal in Java ?
  • ArrayList custom Implementation
  • Difference between volatile and synchronized keyword?
  • How to write thread safe code?

Filed Under: Core Java

Anonymous Inner Class in Java

July 28, 2017 By j2eereference Leave a Comment

Anonymous inner class in Java is a class with no name. Anonymous classes are basically inline (inner class) and are defined inside other classes.  It enables declaration and instantiation of the classes at the same time.

Java Anonymous Inner Classes declaration

Anonymous inner classes are declared and instantiated with a ‘new’ term, at the same time.  These inner classes are declared in a ‘new’ expression, as fraction of a declaration. The declaration appears like a constructor declaration, only that there is a class description limited in a block of code.

Anonymous inner class is a subclass of a class or an anonymous executor of the interface. Hence, an anonymous inner class can request methods only from a parent class reference, described in the reference variable type.

Example of Anonymous Inner Class in Java using Abstract Class

Here is an example of an anonymous inner class that uses Abstract Class. In this example, the anonymous inner class executes an abstract class anonymously.

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
abstract class Man{
abstract void drink();
}
 
public class AnonymousInnerClassTest {
public static void main(String args[])
{
Man m = new Man(){
void drink(){
System.out.println("pure water");
}
};
m.drink();
}
}

Output would be:
pure water

Related Posts

  • How to avoid deadlock in java ?
  • What is deadlock in java?
  • Difference between Serializable and Externalizable
  • Binary search tree implementation in java
  • How HashSet internally works ?
  • BlockingQueue Implementation
  • Implementing PriorityQueue
  • Busy Spinning in mutithreading
  • Implementing queue in java
  • TreeSet vs ConcurrentSkipListSet

Filed Under: Core Java

Network Programming – java.net Package

July 27, 2017 By j2eereference Leave a Comment

Java.net package is composed of (i) classes, (ii) exceptions, and (iii) interfaces that offer a commanding infrastructure for Java networking.

  1. URL

Uniform Resource Locator (URL) signifies a source on the WWW (World Wide Web). A URL can be split up into protocol (http, https, etc), host (authority), port, path (filename), reference and query.

Methods

The URL class offers:

  • Methods for obtaining specific parts (protocol, port, etc) of the provided URL.
  • Methods for deciding whether 2 URL element references have the identical content.
  • Also openConnection( ) method delivers a URLConnection that offers a link to the distant content.

 

  1. URLCONNECTION

The URLConnection class recovers the parts stated by URL elements.

Methods

  • The getContent( ) method is similar to URL class method.
  • URLConnection class also offers methods for obtaining header field estimate. Ex: (i) getContentType( ), (ii) guessContentTypeFromStream( ).
  • Methods getInputStream ( ) that reads information and getOutputStream ( ) for output are offered.
  • Other methods handle the fixing or recovering operations of variables.

 

  1. Socket

A Socket class is the Java depiction of a TCP link. When a Socket is developed, a link is created to a particular destination.

Constructors

Socket constructors support 2 arguments:

  • Host name and
  • Port value.

Methods

  • Methods (i) getInputStream( ), (ii) getOutputStream( ), deliver stream elements that exchange information via socket.
  • Close method orders the primary operating system to shutdown.
  • Few methods obtain information about the link.

 

  1. ServerSocket

ServerSocket denotes a listening TCP link. When a link is requested, this class will deliver a Socket component representing the link.

Constructors

The constructors get the port number as argument for listening the link requests.

Methods

  • The accept( ) method stops the requesting thread until a link is accepted.
  • The close( ) method instructs the system to prevent listening to requests on the socket.
  • There are also methods to recover the host name and port number.

 

  1. DATAGRAMSOCKET

The DatagramSocket signifies a linkless datagram socket. Along with DatagramPacket, this class enables communication utilizing the UDP protocol.

Constructors

As UDP is linkless, port number alone is required and host name is not required for developing a DatagramSocket. There is another constructor that does not obtain arguments.

Methods

Every method acquires a properly created DatagramPacket.

  • send( ) – sends the packet data to the given host and port.
  • receive( ) – stops processing until a packet is obtained by the socket.
  • close( ) – requests the socket to shutdown.
  • getLocalPort( ) – submits the local port number linked with the socket.
  1. DATAGRAMPACKET

DatagramPacket signifies a data packet transmitted by means of UDP protocol (with a DatagramSocket).

Constructors

The DatagramPacket offers 2 constructors for:

  • Incoming packets that picks a byte array as argument and
  • Outgoing packets that picks distant host name and port number as arguments.

Methods

There are 4 methods in the class, they are:

  • getData( ) – retrieves data
  • getLength( ) – retrieves datagram length
  • getAddress( ) – retrieves address
  • getPort( ) – retrieves port number

 

 

  1. INETADDRESS

The InetAddress signifies a host name and its IP values. The class also offers the functionality for acquiring IP value.

Constructors

This class has no clear constructors. Alternatively, static methods getByName( ) and getAllByName( ), are used.

Methods

  • getHostName( ) – delivers a host name that the InetAddress specifies
  • getAddress( ) – delivers an array of the raw bytes of address
  • equals( ) – compares the address objects
  • toString( ) – prints host name and IP address

Related Posts

  • How to create immutable class?
  • Implementing Stack in java
  • What is ReentrantLock?
  • What is Semaphore in java
  • Why AtomicInteger class
  • What is CyclicBarrier?
  • CountDownLatch in java
  • Prototype design pattern
  • Interface changes in java 8
  • Generics wildcard arguments

Filed Under: Core Java

Java Regular Expressions

July 26, 2017 By j2eereference Leave a Comment

Java regular expressions are unique series of characters, which assists in matching or locating other strings or collection of strings, with a unique syntax applied in a pattern. Java offers a regex package for matching with regular expressions.

The java.util.regex package mainly is composed of 3 classes.

  1. Pattern Class

A Pattern element is a compiled form of a regular expression. Pattern class does not offer public constructors. It is used for defining a pattern for the regex mechanism. The following compile methods permit a regular expression as the primary argument.

  • static Pattern compile(String regex) piles up the specified regex and sends the instance of pattern as response.
  • Matcher matcher(CharSequence input) builds a matcher that equals the specified input to the pattern.
  • static boolean matches(String regex, CharSequence input) acts as the blend of compile and matcher methods.
  • String[] split(CharSequence input) divides the input string between matches of specified pattern.
  • String pattern() delivers the regex pattern.

 

  1. Matcher Class

A Matcher element understands the pattern and then executes matching actions against an input string. Matcher class does not offer public constructors. It executes Match Result interface. The matcher methods are:

  • boolean matches() checks if the regular expression equals the pattern.
  • boolean find() locates the subsequent expression that equals the pattern.
  • boolean find(int start) locates the upcoming expression that equals the pattern from the specified start number.
  • String group() delivers the equated subsequence.
  • int start() delivers the first index of the equated subsequence.
  • int end() delivers the final index of the equated subsequence.
  • int groupCount() delivers the total of the equated subsequence.

 

  1. PatternSyntaxException

A PatternSyntaxException element is an unverified exception that points out syntax mistakes in a regular expression pattern. The class methods are:

  • public String getDescription() fetches the report of the mistakes.
  • public int getIndex() fetches the fault index.
  • public String getPattern() fetches the invalid regular expressions.
  • public String getMessage() delivers a multi-line string that contains (i) the report of the error and index, (ii) the invalid pattern, and (iii) a visual sign of the fault index inside the pattern.

Java Regular Expressions Example

In the below example, the regular expressions “.x”, “.x.”, and “..x” are used for finding the occurrence of the string in the given words. Here, a dot signifies a single character. The regular expressions can be written in 3 approaches.

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RGEXP {
public static void main(String args[]) {
 
// Way-1
Pattern s = Pattern.compile(".x");
Matcher a = s.matcher("ox");
boolean y = a.matches();
 
// Way-2
boolean y2 = Pattern.compile(".x.").matcher("oxe").matches();
 
// Way-3
boolean y3 = Pattern.matches("..x", "xx");
 
System.out.println("Regular expression testing " + y + " " + y2 + " " + y3);
}
}

Output for the above program would be

Regular expression testing true true false

In the above example,
• The 1st approach is true as 2nd character is x.
• The 2nd approach is true as 2nd character is x.
• The 3rd approach output is false as it requests for 3rd character and “xx” has only 2 characters.

Related Posts

  • Hashing techniques in java
  • Difference between comparator and comparable
  • Externalization in Java
  • insertion sort algorithm in java
  • Merge sort algorithm in java
  • Quicksort algorithm in java
  • bubble sort algorithm in java
  • Selection Sort in java
  • Access Modifiers in Java
  • Difference between ArrayList and CopyOnWriteArrayList

Filed Under: Core Java

Method Local Inner Class in Java

July 25, 2017 By j2eereference Leave a Comment

Method local inner class in Java is limited to a code section, and it can be processed only inside the same code section it is declared in. Hence it can never execute modifiers. A local inner class instance can be delivered as argument and retrieved from methods, and is available inside a valid scope.

 Purpose of Method Local Inner class

The only limitation in method local inner class is that a local parameter can be executed only when it is defined ‘final’. The basis for this limitation associates primarily to multi-threading problems and makes sure that every variable has definite values when accessed from local inner class. The method executing the local parameters can be called after the execution of the method, within which the local inner class was declared. As a result, the local parameters will no longer retain their values. Hence the values must be fixed before creating the local inner class object. If required, a non-final variable can be copied into a final variable which is subsequently executed by the local inner class.

The following example program will not compile unless the statement System.out.println(b); is eliminated.

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class J2EEReferenceOuterClass {
private int a = 5;
 
public void exampleMethod() {
int b = 10; // here the variable is not declared final
final int c = 20;
 
class J2EEReferenceLocalInnerClass {
public void accessSampleOuter() {
System.out.println(a);
 
System.out.println(b); // (Error: Cannot refer to non-final
// variable b inside an inner class
// defined in a different method)
 
System.out.println(c);
}
}
J2EEReferenceLocalInnerClass innercls = new J2EEReferenceLocalInnerClass();
innercls.accessSampleOuter();
}
}

Java
1
2
3
4
5
6
public class LocalInnerTest {
public static void main(String[] args) {
J2EEReferenceOuterClass outercls = new J2EEReferenceOuterClass();
outercls.exampleMethod();
}
}

OUTPUT

Compilation Error

On declaring the variable ‘b’ as final, the output for the program would be

5

10

20

On eliminating the statement ‘System.out.println(b);’ the output would be,

5

20

 

It is obvious that a method local inner class can never be addressed (i) public, (ii) private, (iii) protected, (iv) static or (v) transient as it is local to a method. Either abstract or final can be applied as modifiers to a method local inner class.

Related Posts

  • Synchronized Map and ConcurrentHashMap
  • Reading file using Java 7 and Java 8
  • Temporal Adjusters in Java 8
  • Period class in Java 8
  • Date in Java 8
  • Singleton in Clustered Environment
  • Enumeration and Iterator
  • Difference between HashMap and HashTable
  • OCJP Quiz
  • JAVA QUIZ

Filed Under: Core Java

URL Processing in Java

July 24, 2017 By j2eereference Leave a Comment

Uniform Resource Locator (URL) signifies a source on the WWW (World Wide Web). A URL can be split up into protocol (http, https, etc), host (authority), port, path (filename), reference and query. URL Processing in Java is done using two classes namely URL Class and URLConnection class.

  1. URL Class

The java.net.URL class includes a collection of methods to operate URL in Java. The URL class contains numerous constructors for building URLs:

  • public URL(String protocol,Stringhost, int port, String file) throws MalformedURLException and generates a URL by bringing the provided parts collectively.
  • public URL(String protocol, String host, String file) throws MalformedURLException , here the standard port for a protocol is used.
  • public URL(String url) throws MalformedURLException generates URL from a String.
  • public URL(URL context, String url) throws MalformedURLException generates URL by syntactically analyzing the string and URL arguments together.

 

The URL class offers the following methods for executing different parts of the URL:

  • public String getPath() delivers the path.
  • public String getQuery() delivers the query portion.
  • public String getAuthority() delivers the authority.
  • public int getPort() delivers the port.
  • public int getDefaultPort() delivers the standard port a protocol.
  • public String getProtocol() delivers the protocol.
  • public String getHost() delivers the host.
  • public String getFile() delivers the filename.
  • public String getRef() delivers the reference.
  • public URLConnection openConnection() throws IOException develops a link to the URL, permitting a user-resource communication.
  1. URLConnection Class

The openConnection mode of URL class provides a URL Connection whose lower classes signify different types of URL connections. i.e., when a URL with http protocol is linked, openConnection mode delivers httpUrlConnection object.

This URLConnection class includes the following methods to fix or fetch information about the connection:

  • Object getContent() and Object getContent(Class[] classes) are used for fetching the corresponding contents of the connection.
  • Methods like (a) String getContentEncoding(), (b) int getContentLength(), (c) String getContentType(), (d) int getLastModified(), (e) long getExpiration(), (f) long getIfModifiedSince() deliver the corresponding estimates of the header field.
  • public void setDoInput(boolean input) method generally has input value to be true as the users normally read from a URLConnection.
  • public void setDoOutput(boolean output) method generally has input value to be false as several forms of URL do not accept writing.
  • public InputStream getInputStream() throws IOException delivers the input stream to read from the source.
  • public OutputStream getOutputStream() throws IOException delivers the output stream to write to the source.
  • public URL getURL() delivers the URL, which is linked to the given URLConnection.

URL Processing in Java Example

Here is a simple example to demonstrate how a URL will be processed in Java:

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.IOException;
import java.net.URL;
 
public class URLProcessingExample {
public static void main(String [] args) {
try {
 
URL url = new URL("http://209.97.166.197/category/design-patterns/");
 
System.out.println(url.toString() +" is the URL");
System.out.println(url.getProtocol()+" is the Protocol");
System.out.println(url.getAuthority()+" is the Authority");
System.out.println(url.getFile()+" is the File Name");
System.out.println(url.getHost()+" is the Host");
System.out.println(url.getPath()+" is the Path");
System.out.println(url.getPort()+" is the Port");
System.out.println(url.getDefaultPort()+" is the Default Port");
 
}catch(IOException e) {
e.printStackTrace();
}
}
}

Output will be:

https://j2eereference.com/category/design-patterns/ is the URL
https is the Protocol
j2eereference.com is the Authority
/category/design-patterns/ is the File Name
j2eereference.com is the Host
/category/design-patterns/ is the Path
-1 is the Port
443 is the Default Port

Related Posts

  • Volatile Keyword in JAVA
  • Setting PDF content properties using iText
  • Using Regular Expression in Java
  • Creating PDF file using itext
  • Accessing Private method outside the class
  • Starting tomcat in Debug mode
  • Scanner
  • Static import
  • String constructors
  • ProcessBuilder

Filed Under: Core Java

Callable and Future Interface

June 20, 2017 By j2eereference Leave a Comment

Callable and Future Interface :

Callable and Future interface has been introduced in JDK 1.5 under java.util.cocurrent package.

Callable interface is used to execute task and is similar to Runnable interface but can return value to caller and is able to throw checked Exception as well .Callable interface has call() method to execute task, computing result and returning result or throws an exception if unable to execute.

Callable interface is used by Executor framework, which contains pool of threads called worker threads then will call submit method of ExecutorService  which is used to execute the Callable tasks by available threads in the pool.

When we submit callable task then returned result is an instance of Future object. This Future object is used to find out the status of callable task ,get the result of task computation or cancel the task.

Example using future and Callable :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
public class CallableDemo {
  private static final int WORKER_THREADS = 10;
  public static void main(String[] args) throws InterruptedException,ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(WORKER_THREADS);
        Future<Integer> futureAdd = executor.submit(new AdditionCallable(10));
        System.out.println("Computation result returned after submitting Callable task "
         + futureAdd.get());
        executor.shutdown();
  }
}
 
class AdditionCallable implements Callable&lt;Integer&gt; {
  Integer n;
  AdditionCallable(Integer n) {
     this.n = n;
  }
 
  @Override
  public Integer call() throws Exception {
   Integer sum = 0;
   for (int i = 0; i <= n; i++) {
       System.out.println("value added in sum is " + i);
       sum += i;
       System.out.println("Updated sum is " + sum);
   }
   return sum;
  }
}

OutPut:

value added in sum is 0
Updated sum is 0
value added in sum is 1
Updated sum is 1
value added in sum is 2
Updated sum is 3
value added in sum is 3
Updated sum is 6
value added in sum is 4
Updated sum is 10
value added in sum is 5
Updated sum is 15
value added in sum is 6
Updated sum is 21
value added in sum is 7
Updated sum is 28
value added in sum is 8
Updated sum is 36
value added in sum is 9
Updated sum is 45
value added in sum is 10
Updated sum is 55
Computation result returned after submitting Callable task 55

Methods of Callable and Future :
1) V call() throws Exception: This method returns result of executable task or throws an exception .
2) Get() :this method is used to get the result of callable task.It is a blocking call which means that if task is not finishes then it will wait until it is finished.
3) get(long timeout, TimeUnit): this method will wait at most the time specified in the method for the task to complete and give results if available.
4) Boolean Cancel() : this method will return true if attempt to cancel the task is successful. If task is already completed or cancelled then attempt will fail.
5) Boolean isCancelled(): this method will return true if task is cancelled before it gets complete.
6) Boolean isDone() : this method will return true if task compeltes.Completion of task can be exception,normal or cancelled.

 

 

Filed Under: concurrent package

Difference between Stack and Heap memory

June 15, 2017 By j2eereference Leave a Comment

Lets see some of the main differences between Stack and Heap memory.

1) Stack memory is used to store local variables and references to other objects in the method whereas heap memory is used to store objects.
2) Size of heap memory is much bigger than the stack memory.
3) Each thread has their own stack which stores local variables and these variables are not accessible globally whereas objects stored in heap are globally accessible.
4) Heap memory size is bigger where we can create and store objects in any order whereas stack memory follows LIFO(Last In First Out) order.
5) We can change the size of heap memory using jvm parameters : -Xms for initial heap memory and –Xmx for maximum heap memory. For stack , use –Xss to specify stack size for each thread.
6) If stack memory is filled up then you will get java.lang.StackOverFlowError . If there is no space left to allocate new Object in Heap memory then you will get java.lang.OutOfMemoryError: Java Heap Space.

Program to generate StackOverFlowError  exception :

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.j2eereference;
public class StackOverflowErrorDemo{
  public static void recursiveComputation(int count)
  {
    if(count == 0)
      return;
    else
      recursiveComputation(++count);
   }
  public static void main(String[] args)
   {
      StackOverflowErrorDemo.recursiveComputation(10);
   }
}

OutPut:
Exception in thread “main” java.lang.StackOverflowError
at com.j2eereference.StackOverflowErrorDemo.recursiveComputation(StackOverflowErrorDemo.java:13)
at com.j2eereference.StackOverflowErrorDemo.recursiveComputation(StackOverflowErrorDemo.java:13)

Program to generate OutOfMemoryError: Java heap space

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.j2eereference;
 
import java.util.ArrayList;
import java.util.List;
public class OutOfMemoryDemo
{
    private static List<String> heapList=new ArrayList<>();
    public static void main(String[] args)
      {
     while(true)
           {
            heapList.add(new String("Shobhna"));  
           }
       }
}

OutPut:
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at com.j2eereference

 

7) Stack memory allocation is simple as compared to heap memory allocation as Stack uses LIFO order,so stack memory is fast as compared to heap memory.
8) Stack memory is used by  only threads whereas heap memory is used by whole application.
9) use stack when you know that how much memory is needed to allocate before compile time on the other hand, use heap if you are not sure about the amount of memory needed at runtime.

Related Posts

  • Assert in java
  • Batch Processing in JDBC
  • Deque in Java Collection
  • Navigable Map
  • Daemon thread
  • Object Cloning in Java
  • varargs in Java
  • Transient Variable
  • Java versions
  • Dynamic Binding and Static Binding in Java

Filed Under: Core Java Tagged With: Difference between Stack and Heap memory, Heap memory, OutOfMemoryError, Stack memory, StackOverFlowError

What is ThreadMXBean in java?

June 14, 2017 By j2eereference Leave a Comment

What is ThreadMXBean :

In the previous article, we have explained about deadlock, why it occurs and how to avoid deadlock condition. Here we will see what is ThreadMXBean and how can it detect deadlock threads. ThreadMXBean  is an interface and belongs to java.lang.Management package. It helps to detect the threads which have entered into deadlock condition and also helps in retrieving details about them.

ThreadMXBean is an interface,  to get an instance of ThreadMXBean use getThreadMXBean() method of ManagementFactory.

Let’s create a program to explain some methods of ThreadMXBean interface.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.j2eereference;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
class ThreadDemo
{
    synchronized void executeMethod1(ThreadDemo demo)
    {
        System.out.println("Thread "+Thread.currentThread().getName()+" is executing");
        demo.executeMethod2(this);
        System.out.println(Thread.currentThread().getName()+" has finished method execution");
    }
   synchronized void executeMethod2(ThreadDemo demo)
    {
     System.out.println("Thread "+Thread.currentThread().getName()+" is executing");
         demo.executeMethod1(this);
         System.out.println(Thread.currentThread().getName()+" has finished method execution");
    }
}
public class ThreadsMXBeanDemo
{
    public static void main(String[] args)
    {
        final ThreadDemo threadDemo1 = new ThreadDemo();
        final ThreadDemo threadDemo2  = new ThreadDemo();
        Thread t1 = new Thread("Thread1")
        {
            public void run()
            {
             threadDemo1.executeMethod1(threadDemo2);
            }
        };
        Thread t2 = new Thread("Thread2")
        {
            @Override
            public void run()
            {
             threadDemo2.executeMethod2(threadDemo1);
            }
        };
        t1.start();
        t2.start();
        ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
        long threadId[] = mxBean.findMonitorDeadlockedThreads();
        if(threadId != null)
        {
            ThreadInfo info[] = mxBean.getThreadInfo(threadId);
            for (ThreadInfo threadInfo : info)
            {
             System.out.println("\nDeadlock Thread details.");
                System.out.println(threadInfo.getThreadId());    
                System.out.println(threadInfo.getThreadName());  
                System.out.println(threadInfo.getLockName());
                System.out.println(threadInfo.getLockOwnerId());
                System.out.println(threadInfo.getLockOwnerName());            
             }
           }
      
            System.out.println("\nGeneral Thread details");
            System.out.println(("Current number of live threads :"+ mxBean.getThreadCount()));
            System.out.println("Total CPU time for the current thread: "+mxBean.getCurrentThreadCpuTime());
            System.out.println("Current number of live daemon threads:"+mxBean.getDaemonThreadCount());
            System.out.println("Peak live thread count :"+mxBean.getPeakThreadCount());
            System.out.println("Total number of threads created and started"
            +mxBean.getTotalStartedThreadCount());
          }
}

OutPut :

Thread Thread1 is executing
Thread Thread2 is executing

Deadlock Thread details.
11
Thread2
com.j2eereference.ThreadDemo@15db9742
10
Thread1

Deadlock Thread details.
10
Thread1
com.j2eereference.ThreadDemo@6d06d69c
11
Thread2

General Thread details
Current number of live threads :7
Total CPU time for the current thread: 46800300
Current number of live daemon threads:4
Peak live thread count :7
Total number of threads created and started7

Important methods of ThreadMXBean:

findMonitorDeadlockedThreads(): This method will return number threads that are in deadlock state and waiting to acquire object monitors.
getThreadId(): This method will return the unique ID of thread
getThreadName(): This method will return the thread name
getLockName(): this method will reurn the string representation of an object for which associated thread is blocked waiting.
getLockOwnerId(): This method will return the ID of the thread which owns the object lock
getLockOwnerName(): This method will return the the name of the thread which owns the object lock.
getThreadCount(): This method will return number of live threads including both daemon and non-daemon threads.
getCurrentThreadCpuTime(): This method will return total CPU time for the current thread in
getDaemonThreadCount(): This method will return current number of live daemon threads.
getPeakThreadCount(): This method will return the peak live thread count since the Java virtual machine has been started .

Related Posts

  • Creating log in XML format
  • Shutdown Hooks API
  • User defined exception in java
  • Different ways of creating object in java
  • Immutable Object
  • Comparable Interface
  • Optimize j2ee Application
  • Optimizing Loop
  • Generics
  • Autoboxing

Filed Under: Core Java Tagged With: Deadlock detection, ManagementFactory, ThreadMXBean, ThreadMXBean Interface

What is serialVersionUID

June 13, 2017 By j2eereference Leave a Comment

What is serialVersionUID?  In serialization process at runtime each serializable class is associated with a version number, called a serialVersionUID, and this versionUID is used to ensure that during deserialization the same class is loaded which was used during serialization process.  If  serialVersionUID is not declared explicitly then JVM will do it for you automatically.

Problem occur if not defining serialVersionUID: serialVersionUID is used to control the version of class.If serialVersionUID is not declared in the class and if there is any incompatible modification made in class, then we would not be able to deserialize this class as serialVersionUID generated by java compiler for modified class will be different from old serialized class and deserialization process will throw java.io.InvalidClassException.

In below example, we commented serialVersionUID and serialized class StudentInformation

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
 
class StudentInformation implements Serializable
{
   // private static final long serialVersionUID = 1L;
   private Integer rollNo;
   private String name;
   public StudentInformation()
   {
      System.out.println("No argument constructor is called");
   }
  
   public StudentInformation(Integer rollNo,String name)
   {
      System.out.println("Parameterised constructor is called");
      this.rollNo = rollNo;
      this.name = name;
   }
   @Override
   public String toString()
   {
      return "Student Information is rollNo : " + rollNo + "and Student name is : "+name ;
   }
}
 
public class SerializableDemo
{
   public static void main(String[] args)
   {
     StudentInformation object1 = new StudentInformation(21,"Shobhna");
     try {
           OutputStream fout = new FileOutputStream("ser.txt");
           ObjectOutput oout = new ObjectOutputStream(fout);
           System.out.println("Serializing StudentInformation object");
           oout.writeObject(object1);
           fout.close();
           oout.close();
           System.out.println("Serialization process completed.");
           InputStream inputStream=new FileInputStream("ser.txt");
 
         } catch (IOException e)
         {
           e.printStackTrace();
         }
    }
}

OutPut:

Parameterised constructor is called
Serializing StudentInformation object
Serialization process completed.

Now, modify this class by adding field address and do not serialize class again as given below

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
 
class StudentInformation implements  Serializable
{
  private Integer rollNo;
  private String name;
  private String address;
  public StudentInformation()
  {
    System.out.println("No argument constructor is called");
  }
  public StudentInformation(Integer rollNo,String name)
  {
    System.out.println("Parameterised constructor is called");
    this.rollNo = rollNo;
    this.name = name;
   }
   @Override
   public String toString()
   {
     return "Student Information is rollNo : " + rollNo + "and Student name is : "+name ;
   }
}
public class SerializableDemo
{
  public static void main(String[] args)
  {
    StudentInformation object1 = new StudentInformation(21,"Shobhna");
  }
}
 

OutPut:

Parameterised constructor is called

Now , try to deserialize the saved class StudentInformation  , you will get InvalidClassException

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
 
class StudentInformation implements  Serializable
{
  // private static final long serialVersionUID = 1L;
  private Integer rollNo;
  private String name;
  private String address;
  public StudentInformation()
  {
    System.out.println("No argument constructor is called");
  }
 public StudentInformation(Integer rollNo,String name)
  {
    System.out.println("Parameterised constructor is called");
    this.rollNo = rollNo;
    this.name = name;
  }
  @Override
  public String toString()
  {
    return "Student Information is rollNo : " + rollNo + "and Student name is : "+name ;
  }
}
 
public class SerializableDemo
{
  public static void main(String[] args)
  {
    try {
          InputStream inputStream=new FileInputStream("ser.txt");
          ObjectInput outInput=new ObjectInputStream(inputStream);
          System.out.println("\nDeSerializing StudentInformation objects");
          StudentInformation std=(StudentInformation)outInput.readObject();
          System.out.println(std);
          inputStream.close();
          outInput.close();
          System.out.println("Object DeSerialization completed.");
         } catch (Exception e) {
             e.printStackTrace();
        }
   }
}

Java
1
2
3
4
5
6
7
8
9
10
11
<span style="text-decoration: underline;"><strong>OutPut:</strong></span>
java.io.InvalidClassException: StudentInformation; local class incompatible:
stream classdesc serialVersionUID = 8086333747608896269,
local class serialVersionUID = -2722271583385024093
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:616)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1623)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at SerializableDemo.main(SerializableDemo.java:57)

 

Related Posts

  • TreeSet
  • Interaction between Threads
  • Features added in Java 1.7
  • LinkedList
  • Enums
  • Interface
  • Features added in JDBC 4.1
  • HashMap
  • Synchronization
  • Abstract class and methods

Filed Under: Core Java Tagged With: impact of serialVersionUID, serialVersionUID

  • Page 1
  • Page 2
  • Page 3
  • …
  • Page 13
  • Next Page »

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.