Loading...

Follow Java Hungry on Feedspot

Continue with Google
Continue with Facebook
or

Valid
Producer Consumer design pattern is an example of concurrency pattern in Java. The solution of the producer consumer problem can be classic wait and notify thread operations that are commonly used in multi-threading but in this article, we will deal with this by using the BlockingQueue implementation which was introduced in Java 5.

The BlockingQueue interface can be found inside the java.util.concurrent package. There are many BlockingQueueimplementations provided by Java like LinkedBlockingQueue, PriorityBlockingQueue, ArrayBlockingQueue and SynchronousQueue which are all thread safe.

Read Also :  What is Thread Synchronization in Java
IntroductionProducer Consumer design pattern has two threads namely: the Producer and the Consumer. These threads are linked by a common buffer which is basically a queue.
Both the threads are independent in their nature of work. The producer will generate the data, put it in the queue and keep on repeating the same process. The consumer will keep on consuming or using the data by removing it from the queue.
Producer Consumer Problem:The main problem to understand here is if the queue or buffer is full, the producer should not try to put any more data on it. Similarly, if the queue is empty then the consumer should not try to extract or remove data from the empty queue.
Solution:The BlockingQueue interface provides two methods put() and take() which are used implicitly in blocking the Producer and the Consumer thread respectively. The thread (Consumer) trying to remove item from an empty queue waits or is blocked until the Producer thread adds an item to the queue. Similarly, the thread (Producer) trying to add an item to a full queue is blocked until any Consumer thread makes some space in the queue by removing the item(s) from the queue.
Producer Consumer Solution using BlockingQueue Example: Producer Class

The code snippet given below represents a typical Producer class generating some data and putting it in the BlockingQueue. If the buffer is full, it will wait for the Consumer thread to remove some data from the queue before resuming its operation again. We are trying to generate some Integer value as the data here in this example.

package com.javahungry; 
import java.util.concurrent.BlockingQueue;

class Producer implements Runnable {

private final BlockingQueue<Integer> blockingQueue;

public Producer(BlockingQueue<Integer> blockingQueue) {
this.blockingQueue = blockingQueue;
}

public void run() {
for (int i = 10; i <= 100; i += 10) {
try {
System.out.println("Data produced : " + i);
blockingQueue.put(i);
} catch (InterruptedException ex) {
System.out.println("Producer thread interrupted.");
}
}
}
}


Consumer Class

The code snippet given below represents a Consumer class that removes the data from queue and does some processing on it. If the buffer is empty, it will wait until the Producer thread generates and puts some data into the queue.


package com.javahungry; 
import java.util.concurrent.BlockingQueue;

class Consumer implements Runnable {

private final BlockingQueue<Integer> blockingQueue;

public Consumer(BlockingQueue<Integer> blockingQueue) {
this.blockingQueue = blockingQueue;
}

public void run() {
while (true) {
try {
System.out.println("Data consumed : " + blockingQueue.take());
} catch (InterruptedException ex) {
System.out.println("Consumer thread interrupted.");
}
}
}
}


Testing the Solution using main class:We will now test the solution that we have created using BlockingQueue. As you can see below, we have created a shared BlockingQueue in which the Producer thread will put the data and the same data will be consumed by the Consumer thread. Here, we have used LinkedBlockingQueue class to implement the BlockingQueue interface. Further, we create the Producer and the Consumer thread, start them and observe the result.


package com.javahungry;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumerExample {

public static void main(String[] args) {

// Common buffer created using LinkedBlockingQueue
BlockingQueue<Integer> blockingQueue =  
                                  new LinkedBlockingQueue<Integer>();

// Producer thread creation
Thread producer = new Thread(new Producer(blockingQueue));

// Consumer thread creation
Thread consumer = new Thread(new Consumer(blockingQueue));

// Start Producer and Consumer thread
producer.start();
consumer.start();

}

}


Output:
Data produced : 10
Data produced : 20
Data consumed : 10
Data produced : 30
Data consumed : 20
Data produced : 40
Data consumed : 30
Data produced : 50
Data consumed : 40
Data consumed : 50
Data produced : 60
Data produced : 70
Data consumed : 60
Data produced : 80
Data consumed : 70
Data produced : 90
Data produced : 100
Data consumed : 80
Data consumed : 90
Data consumed : 100

It is evident from the above output that the data is getting generated and consumed smoothly in a First-In, First-Out order as it is the feature of LinkedBlockingQueue. The Producer thread is creating the data, putting it in the queue and Consumer thread is removing it from the data implicitly without any need to write and notify statements. This wraps up this article on Producer Consumer Problem in Java using multithreading (BlockingQueue).

References:
Java doc
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
In this post I will be sharing what is Special number, examples of Special number, algorithm and java program to check whether a given number is Special number or not.

Read Also :  Happy Number Program in Java
What is Special NumberA number is known as Special number when sum of the factorial of digits is equal to the original number (given number).

Examples:

Below are examples of numbers which are Special

Number to check : 145 
1! +4! + 5! = 1 + 24 + 120 = 145   // 145 is a Special Number
 
Number to check : 2 
2!  = 2 = 2   // 2 is a Special Number

Below are examples of numbers which are NOT Special number

Number to check : 35 
3! + 5! = 6 + 120 = 126   // 35 is NOT a Special Number
 
Number to check : 105 
1! + 0! + 5! = 1 + 1 + 120 = 122   // 105 is NOT a Special Number

Read Also :  Disarium Number Program in Java

Java Program for Special Number
import java.util.*;

public class JavaHungry {

public static void main(String args[]) {
System.out.println("Enter any number : ");
Scanner scan = new Scanner(System.in);
int inputNumber = scan.nextInt();
boolean result = specialnumber(inputNumber);
if (result == true)
System.out.println(inputNumber + " is a Special number");
if (result == false)
System.out.println(inputNumber + " is NOT a Special number");
}

public static boolean specialnumber(int inputNumber) { 
 
        // Create a copy of the inputNumber 
        int temp = inputNumber;
 
        // Initialize sumOfDigits of inputNumber
int sumOfDigits = 0; 
 
        /* Calculate the sum of factorial of
           digits */ 
        while (temp != 0) { 
           // Get the rightmost digit 
            int currentDigit = temp % 10;
sumOfDigits = sumOfDigits + factorial(currentDigit);
temp = temp/10;
        /* If sumOfDigits is equal to inputNumber then 
the number is Special, otherwise not */
        return (sumOfDigits == inputNumber);
}

public static int factorial(int number) {
if (number == 1 || number == 0)
return 1;
else
return (number * factorial(number -1));
}
}

Output :
Enter any number : 145
145 is a Special number
Algorithm for Special Number1. Create a copy of the inputNumber (original number) by storing its value in variable temp.

2. Initialize sumOfDigits variable value to 0. It will represent the sum of factorial of digits.

3. Using while loop
    a. Get the rightmost digit of variable temp by using (temp %10). Store its value in variable currentDigit.
    b. Calculate the factorial of the currentDigit .
    c. add the value of factorial method to sumOfDigits variable.

4. Check whether the variable sumOfDigits is equal to inputNumber (original number).
     a. If both are equal then the inputNumber is Special.
     b. Otherwise, the inputNumber is not a Special number.

That's all for the day, please mention in comments if you know any other way to implement Special number program in java.
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
In this post I will be sharing what is Disarium number, examples of Disarium number , algorithm and program in java to check whether a given number is Disarium or not.

Read Also :  Happy Number Program in Java
What is Disarium NumberDisarium number can be defined as a number whose sum of digits, powered with their respective position, is equal to the original number.

Examples:

Below are examples of number which are Disarium

Number to check : 89 
81+92 = 8 + 81 = 89           // 89 is a Disarium Number
 
Number to check : 135 
11+32+53 = 1 + 9 + 125 = 135  //135 is a Disarium Number
 
Number to check : 175 
11+72+53 = 1 + 49 + 125 = 175 //175 is a Disarium Number
 
Number to check : 518 
51+12+83= 5 + 1 + 512 = 518   //518 is a Disarium Number

Below are examples of number which are NOT Disarium

Number to check : 19 
11+92 = 1 + 81 = 82           // 19 is not a Disarium Number
 
Number to check : 134 
11+32+43 = 1 + 9 + 64 = 74    //134 is not a Disarium Number
 
Number to check : 176 
11+72+63 = 1 + 49 + 216 = 266 //176 is not a Disarium Number
 
Number to check : 512  
51+12+23= 5 + 1 + 8 = 14      //512 is not a Disarium Number


Read Also :  Pronic Number Program in Java

Java Program for Disarium Number
import java.util.*;

public class JavaHungry {
public static void main(String args[]) {
        System.out.println("Input number : ");
Scanner scan = new Scanner(System.in);
int inputNumber = scan.nextInt();
Boolean result = checkDisarium(inputNumber);
if (result == true)
System.out.print(inputNumber + " is a Disarium number");
else
System.out.print(inputNumber + " is not a Disarium number");
}

public static boolean checkDisarium(int inputNumber) {
        //Calculate number of digits in the inputNumber
int numOfDigits = Integer.toString(inputNumber).length();

// Initialize sumOfDigits of inputNumber
int sumOfDigits = 0;

// Create a copy of the inputNumber
int num = inputNumber;

/* Calculate the sum of digits powered
with their respective position */
while (num != 0) {
// Get the rightmost digit
int currentDigit = num % 10;
sumOfDigits = (int) (sumOfDigits + Math.pow(currentDigit, numOfDigits));
numOfDigits--;
num = num / 10;
}
/* If sumOfDigits is same as inputNumber then
the number is Disarium, otherwise not */
return (sumOfDigits == inputNumber);
}
}

Output :
Input number : 135
135 is a Disarium number 

Algorithm for Disarium Number1. Calculate number of digits present in the inputNumber(original number) by using length() method.

2. Initialize sumOfDigits variable to 0 as it will represent the sum of the digits powered with their respective position.

3. Create a copy of inputNumber (original number) by storing its value in variable num.

4. Using while loop

     a. Get the rightmost digit of variable num by using (num % 10). Store its value in variable    currentDigit.
     b. Use Math.pow() function and calculate the value of currentDigit raised to power its position.
     c. add the value of Math.pow() function to sumOfDigits variable. 

5. Check whether the variable sumOfDigits is equal to inputNumber (original number).

     a. If both are equal then the inputNumber is Disarium.
     b. Otherwise, the inputNumber is not a Disarium number.

That's all for the day , please mention in comments if you know any other way to implement Disarium number program in java.
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Today we are going to understand the difference between String , StringBuilder and StringBuffer . It is one of the most popular String interview question for beginners. As you will find that there are minor differences between the above mentioned classes.
StringString is immutable  ( once created can not be changed ) object. The object created as a String is stored in the  Constant String Pool.
Every immutable object in Java is thread-safe, that implies String is also thread-safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed.

String  demo = "hello" ;

// The above object is stored in constant string pool and its value can not be modified.

demo="Bye" ;

//new "Bye" string is created in constant pool and referenced by the demo variable           

// "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string 

StringBufferStringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread-safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread-safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;

// The above object stored in heap and its value can be changed .

demo1 = new StringBuffer("Bye");

// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilderStringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is  not thread safe. 
StringBuilder is fast as it is not thread safe . 

StringBuilder demo2= new StringBuilder("Hello");

// The above object too is stored in the heap and its value can be modified

demo2=new StringBuilder("Bye"); 

// Above statement is right as it modifies the value which is allowed in the StringBuilder


----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                
Storage Area | Constant String Pool           Heap                       Heap
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Slow                       Slow but faster             Fast
                                                                   than String     
-----------------------------------------------------------------------------------


Please mention in the comments in case you have any doubts related to the post: difference between string, stringbuffer  and stringbuilder.

References :
String Java Doc
StringBuffer Java Doc
StringBuilder Java Doc 
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
In this article, I will discuss about a common issue encountered by developers who work on any javascript code, be it regular JavaScript, jQuery or Angular js.

Problem:
"Uncaught ReferenceError: $ is not defined"
In various cases, when any piece of code is making use of any jQuery functionality, there are high chances of receiving "Uncaught ReferenceError: $ is not defined" error.

$ represents jQuery function of jQuery. We get this error whenever a call to jQuery method is made before jQuery has been loaded.

Let’s have a look at couple of different syntax that can be interchangeably used.

$("#age").hide()

jQuery("#age").hide()

Both of the lines written above hide the field with id= “age” so it is up to an individual to decide which syntax he wants to use.

There are multiple reasons due to which this error can pop up which will be discussed further along with their respective solutions.
[Fixed] Uncaught ReferenceError: $ is not defined
1. Include jQuery script file in the code before including any scripts or files that refer jQuery

We may have multiple script files being called in the code. If we have any such file which has a dependency on jQuery file, then jQuery file should be included before such files as scripts are loaded in the sequence in which they are written in the code.

<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js">
</script>
// loads jquery-ui script first


<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
 //loads jquery library after the dependent library jquery-ui

Consider the sequence of scripts above. jquery-ui uses jQuery functionality by using $ shorthand and if the main jQuery script is not loaded by the time jquery-ui script is called then we come across “Uncaught ReferenceError: $ is not defined” error so as the solution, the above sequence should be changed to the one given below.

<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
// let jQuery be loaded first


<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js">
</script> 
// load dependent scripts later

Now, jquery-ui file will be able to find $ reference as the jQuery has already been loaded before it is referenced from jquery-ui.

2.  Check internet availability

Sometimes the reason for getting this error can be unavailability of internet. When we have jQuery scripts directly being referred from internet like Microsoft or Google CDN and we are offline so the code is not able to access the required URL via internet. This may lead to “Uncaught ReferenceError: $ is not defined” error.

As a solution, we should either ensure internet connectivity when the code is running.

Alternatively, we can also have jQuery file downloaded and placed in the local file system from where the code can access it without the need to connect to the internet.

Below script is being loaded directly from Google CDN. If internet is not available when it is loaded then it will give us the error.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script> 

We can download the above jQuery file from its URL and place it inside our project. We have an example below where it is kept inside lib folder of the project.

<script src="/lib/jquery.min.js"></script>

3.  Correct the path from which the jQuery script is loaded

Sometimes this error can occur because the path to jQuery script file does not exist. It can happen because of the two very common reasons.

Firstly, the path which is being referred might not be hosting the jQuery file anymore and we might need to refer to a new path.

Secondly, it can also occur if we have given wrong reference due to some spelling mistake.

In both the cases, the browser will not be able to load the required script which will again lead to "Uncaught ReferenceError: $ is not defined" error.

This can be fixed by correcting the jQuery file’s path in case it is spelt incorrectly or by configuring a new path to load the library in case it has been moved from an existing location to a new location.

This concludes the article on "Uncaught ReferenceError: $ is not defined" error. Please mention in the comments in case you have any questions.
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Java Hungry by Subham Mittal - 1M ago
In this post we will learn about the pronic number program in java. In this post I will be sharing what is pronic number, algorithm , java program  and points to remember about pronic number.
What is Pronic Number A pronic number is a number which is represented by the product of two consecutive numbers , that is a number of the form "n x (n+1)". They are also called rectangular numbers, oblong numbers and heteromecic numbers.

Examples :

Number to check : 12
3 x 4 = 12 // 12 is a pronic number
 
Number to check : 20 
4 x 5 = 20  // 20 is a pronic number
 
Number to check : 30 
5 x 6 = 30  // 30 is a pronic number   
 
Number to check : 48
6 x 8 = 48  // 48 is not a pronic number  

Pronic numbers upto 100 are : 0, 2, 6, 12, 20, 30, 42, 56, 72, 90 etc.

Read Also :  Happy Number Program in Java
Algorithm to find Pronic Number 1. Check number N is pronic or not.
2. Calculate the square root K of the given number N.
3. Multiply K * (K+1), if result is equal to the  number N, then N is a pronic number otherwise not.
Java Program to find Pronic Number
import java.util.*;
public class JavaHungry { 
 
    public static void main(String args[]) { 
        
        System.out.println("Enter input number ");
Scanner sc = new Scanner(System.in);
int inputNumber = sc.nextInt();
int sqrtNum = (int) Math.sqrt(inputNumber);
int product = sqrtNum * (sqrtNum + 1);
if (product == inputNumber)
System.out.println("Pronic Number");
else
System.out.println("Not a Pronic Number"); 
 
   }
}

Points to Remember :1.  According to Wikipedia, all pronic numbers are even. 2 is the only prime pronic number.

2.  If number 25 is appended to the decimal representation of any pronic number, the outcome will always be a square number.

Examples : 
625 = 252     // 6 is a pronic number , 25 appended = 625 is a square number.
1225 = 352  // 12 is a pronic number , 25 appended = 1225 is a square number.

That's all for today, please mention in comments if you know any other way to check pronic number in java.
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Java 12 was launched by Oracle on 19th, March 2019. It comes as a part of Java’s six monthly release cadence and it is a non-long term support (LTS) version contrary to Java 11 which was an LTS version. We will keep on getting the new releases every six months. This will help the developers in getting the access to the latest updates like new APIs and methods, JVM updates and so on.
Let’s have a look at the major features and enhancement introduced in JDK 12.

Read Also :  Java 11 features and enhancements

1. String API Changes1.1 String constantsIn JDK 12, two new interfaces, java.lang.constant.Constable and java.lang.constant.ConstantDesc have been implemented inside the String class. Each of these interfaces from Constants API has a method declared inside it with String class providing implementation for both of them. Let’s have a look at these two, newly introduced methods.

1.1.1 Optional describeConstable()
 
describeConstable() is a public method from Constable interface. It has been implemented in String class and it returns an Optional object describing the String’s instance. It contains the nominal descriptor of the String instance on which this method is called upon. The nominal descriptor for String instance is the instance itself.
 
Example: 

String str = "JavaHungry";
Optional optional = str.describeConstable();
System.out.println(optional);
System.out.println(optional.get());
Output:
Optional[JavaHungry]
JavaHungry

1.1.2 String resolveConstantDesc(MethodHandles.Lookup lookup)
 
resolveConstantDesc() is a public method from ConstantDesc interface which has been implemented inside String class. It resolves the String instance on which it is called as ConstantDesc and outcome of it is the String instance itself.
 
Example:
 
String str = "JavaHungry";
String constantDesc = str. resolveConstantDesc(MethodHandles.lookup());
System.out.println(constantDesc.equals(str));
System.out.println(constantDesc);

Output:
true
JavaHungry


1.2  String.indent(int n) methodThis method adjusts the indentation of each line of the String based on the input value of n.
If the value of n is positive then it inserts n whitespaces at the beginning of each line. If the value of n is negative then it removes n whitespaces from the beginning of each line.

Example:

String str = "Java\nHungry\nBlog".indent(2);
System.out.println(str);

Output:

//  Java
//  Hungry
//  Blog
2. Switch Expressions (Preview) : (JEP 325) This is a preview language feature. It enables switch statement to be used as a statement as well as an expression. This feature paves the way for the usage of Pattern Matching in switch. Using switch expression will make the code more compact and increase it readability at the same time. The syntax is “case L ->”. Let’s check the switch expression example below.

int numberOfDays = switch (month) {
case JAN, MAR, MAY,JUL,AUG,OCT,DEC -> 31;
case APR,JUNE,SEP,NOV -> 30;
case FEB -> 28;
default -> throw new IllegalStateException(“Invalid month”);
};

The switch expressions do not have a fall through and there is no need of break statement in such cases. The code on the right side of the switch label can be a block, an expression or even a throw statement. It will only be executed if the label is matched. The “default” case has been made compulsory for switch expressions.

3. Shenandoah: A Low-Pause-Time Garbage Collector (Experimental) : (JEP 189)  It is an experimental feature. Shenandoah garbage collector was initiated in 2014 by Red Hat and it aims at reducing the garbage collection pause times. It is designed to run concurrently with the other Java application threads. In Shenandoah GC, pause times do not depend on the heap size which means Shenandoah has short, consistent pause time and size of the heap does not matter.
4. Microbenchmark Suite : (JEP 230) A microbenchmark suite based on Java Microbenchmarking Harness (JMH) has been added to the Java source code. It will help the developers in creating new microbenchmarks as well as run the existing ones.

5. JVM Constants API : (JEP 334)A new java.lang.invoke.constant package has been introduced in Java 12 under JEP 334. As we know, there is a constant pool associated with every Java class file. It mainly stores the operands for bytecode instruction in the class. The entries in this pool are known as “Loadable constants” and they can describe simple values like strings or run time artifacts like methods and classes. A program that needs to manipulate the class files would need to model the loadable constants which not an easy task if the loadable constant describes a class. JVM Constants API would be of great importance in such cases as it has a pre-defined group of symbolic reference types which can define all types of loadable constants in a purely nominal form.
6. One AArch64 Port, Not Two : (JEP 340) Before Java 12, two ports existed for 64-bit ARM architecture in OpenJDK, one contributed by Oracle and another by Red Hat. As part of JEP 340, the port provided by Red Hat will be a default build as the build option for this port have been removed in Java 12. The 64 bit ARM implementation provided by Oracle will be removed. This has been done to remove the redundant effort required in maintaining two similar ports.
7. Default CDS Archives : (JEP 341) CDS stands for Class Data Sharing and it is one of the commercial features inside Oracle JDK. It has now been included in OpenJDK as well with a view to have both the binaries as same as possible.
For 64-bit version of JDK 12, there will be no need to run –Xshare:dump command explicitly to use the CDS feature. As part of this JEP, JDK build has been modified to run java –Xshare:dump command after the JDK image has been linked. This feature will also ensure a reduced start up time and memory footprint. Also, CDS will be ON by default from Java 12 onwards. The default shared archive file “classes.jsa” can be found inside the /bin/server folder. This file is the default CDS archive that has been generated using the default class list.

8. Abortable Mixed Collections for G1 : (JEP 344) This change has been introduced to make G1 garbage collector more efficient. G1 garbage collector divides the heap memory space into regions. Based on its pause prediction model and previous collection data, G1 predicts the number or set of regions that can be collected within the specified pause time target. These regions which are marked for collection are called “collection set”.
Before Java 12, if G1 starts the collection operation on a collection set, then it must finish the process without stopping. This could lead G1 into exceeding the pause time target set by the user if the collection set is large. It is here that the JEP 344 comes into picture. As per this feature, if the scenarios of selecting wrong number of regions are frequent, then G1 will do the collection work in steps, incrementally and it will abort the collection after every step if needed. This would ultimately result in G1 achieving a better pause time goal.
9. Promptly Return Unused Committed Memory from G1 : (JEP 346) This feature is again aimed at enhancing G1 garbage collector. In the current scenario, G1 returns Java heap memory back to operating system only in case of full garbage collection or during a concurrent cycle. G1 generally avoids full GC and the interval in which concurrent cycles are triggered is dependent on heap memory being currently used by the application. This may lead to instances where G1 does not release committed heap memory to operating system if the application is idle.
As part of JEP 346 in Java 12, G1 will now try to continue or start concurrent cycle periodically, if it finds the application to be inactive or idle. This will enable G1 to return the unused heap memory to the operating system in a more efficient way.

That's all for the java 12 features and new enhancements. Please mention in the comments if you have any questions related to the java 12.

References :
String Java doc
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Multi-threading in java is a vast topic. I have already shared frequently asked interview questions on multi-threading. In this post we will learn about what is synchronization and synchronized block in java in detail. So let's start by understanding the term "Synchronization" first. 

Read Also :  Multi-threading Interview Questions
What is Synchronization?Synchronization in java is a technique to prevent concurrent access of any shared resource in a multi-threaded environment.
Why Synchronization?In multi-threaded environment, we may come across a situation where two or more threads try to gain access to the same resource and try updating it. This may lead to unexpected outcomes, inconsistencies and errors.
Therefore, it becomes important that one and only one thread should access such a resource at any given point of time and this is achieved by thread synchronization. It is important to note that if the shared resource is mutable and multiple threads are accessing it, then only synchronization is required. In case of immutable or read only objects, synchronization is not required as there will be no change to the state of the object.

Thread synchronization can be achieved using different strategies like using synchronized methods, synchronized blocks and inter-thread communication. In this article, we will discuss only about synchronized blocks in Java.

Multi-threading without Synchronization:Let’s first see the below example where two threads are trying to access the same method of the shared object in an unsynchronized way.

package com.javahungry;

class Counter {
void printValue(String threadName) {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName +  
                        " with counter value --> " + i);
try {
Thread.sleep(200);
   catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}

public class NotSynchronizedDemo {

public static void main(String[] args) {

final Counter counter = new Counter();
Thread t1 = new Thread("Thread 1") {
public void run() {
counter.printValue(Thread.currentThread().getName());
}
};

Thread t2 = new Thread("Thread 2") {
public void run() {
counter.printValue(Thread.currentThread().getName());
}
};

t1.start();
t2.start();
}

}

Output:

Thread 1 with counter value --> 1
Thread 2 with counter value --> 1
Thread 1 with counter value --> 2
Thread 2 with counter value --> 2
Thread 2 with counter value --> 3
Thread 1 with counter value --> 3
Thread 1 with counter value --> 4
Thread 2 with counter value --> 4
Thread 2 with counter value --> 5
Thread 1 with counter value --> 5

As it is evident from above output, both of the threads have unsynchronized concurrent access to the shared method. The threads do not wait for the other thread to finish its execution and enter the common piece of code. This results in thread interference which can lead to data corruption and inconsistency. We will now see how to prevent this using java synchronized block.
Synchronized block:A piece of code marked with synchronized keyword is known as Synchronized block. The shared resources that need to be synchronized are placed inside it to prevent concurrency related issues in case of multithreading. Java uses concept of monitors to achieve synchronization. Every object in Java has an associated monitor which can be locked or unlocked by a thread.

Syntax:

synchronized(objectReference){

//the code goes here

}

The argument in parentheses is called monitor object and the code is synchronized on this object. Only one thread can obtain a lock on this monitor object at any given point of time. The synchronized block may throw NullPointerException if the monitor object passed as the argument to the synchronized block is null.
Synchronized block inside instance method:The term “synchronized block” normally applies to synchronized block inside instance method. It is used to synchronize a block of code inside a non-static method.

Example:

public void displayCount(int count) {

//synchronized block starts
synchronized (this)
{
count++;
System.out.println(count);
}
//synchronized block ends

}

The instance which invokes the method having synchronized block is the monitor object and its lock is associated with the monitor. This instance has been denoted by “this” keyword in the above example. Only one thread will be able to execute the code inside synchronized code block for the same monitor object.

Multithreading using synchronized block inside instance method:
package com.javahungry;

class Counter {
void printValue(String threadName) {
synchronized (this) {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName +  
                                " with counter value --> " + i);
try {
Thread.sleep(200);
    catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}
}

public class SynchronizedDemo {

public static void main(String[] args) {

final Counter counter = new Counter();
Thread t1 = new Thread("Thread 1") {
public void run() {
counter.printValue(Thread.currentThread().getName());
}
};

Thread t2 = new Thread("Thread 2") {
public void run() {
counter.printValue(Thread.currentThread().getName());
}
};

t1.start();
t2.start();
}

}


Output:

Thread 1 with counter value --> 1
Thread 1 with counter value --> 2
Thread 1 with counter value --> 3
Thread 1 with counter value --> 4
Thread 1 with counter value --> 5
Thread 2 with counter value --> 1
Thread 2 with counter value --> 2
Thread 2 with counter value --> 3
Thread 2 with counter value --> 4
Thread 2 with counter value --> 5

As we can see from the result above, Thread 1 starts its execution and once it finishes only then Thread 2 starts executing. Keeping the code inside synchronized block has solved the problem that we faced when the same block of code was not synchronized and we got inconsistent output.
Synchronized block inside static method:It is also known as static synchronization and is used to synchronize the code block inside a static method.

Example:
 
public static void displayCount(int count) {

//synchronized block inside static starts
synchronized (Counter.class) {
count++;
System.out.println(count);
}
//synchronized block inside static ends
}

In case of synchronized block inside a static method, the monitor object is the class itself. We pass .class as the argument for the synchronized block in this case. In case of multiple instances of a class, only one thread can execute the code inside synchronized block in any of the available instances of such a class. This is called Class level locking and is done to keep static information thread safe.

Multithreading using synchronized block inside static method:
package com.javahungry;

class Counter {
static void printValue(String threadName) {
synchronized (Counter.class) {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + 
                                " with counter value --> " + i);
try {
Thread.sleep(200);
    catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}
}

public class StaticSynchronizedDemo {

public static void main(String[] args) {

Thread t1 = new Thread("Thread 1") {
public void run() {
Counter.printValue(Thread.currentThread().getName());
}
};

Thread t2 = new Thread("Thread 2") {
public void run() {
Counter.printValue(Thread.currentThread().getName());
}
};

t1.start();
t2.start();
}

}

Output:

Thread 1 with counter value --> 1
Thread 1 with counter value --> 2
Thread 1 with counter value --> 3
Thread 1 with counter value --> 4
Thread 1 with counter value --> 5
Thread 2 with counter value --> 1
Thread 2 with counter value --> 2
Thread 2 with counter value --> 3
Thread 2 with counter value --> 4
Thread 2 with counter value --> 5

From the above results, it is evident that the threads are processing the code in a synchronized way in case of static method having synchronized block inside it. At a time, one thread gets access to the synchronized code inside printValue() method, it executes the logic while the other thread waits. Once the first thread to enter the synchronized logic finishes its execution, the next thread get the access and starts it execution.

That's all for the post thread synchronization and synchronized block in java. Please mention in the comments in case you have any questions.

Reference :
Java Synchronization doc
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
In this blog post we will learn about happy number program in java. Happy numbers definition depends on the decimal representation (base 10) of the number. The definition of happy numbers can be extended to other bases for e.g base 5. In this article I will be sharing what is Happy number, what is unhappy number(sad number) with examples and the program to check happy number in java.
What is Happy number
Any positive number greater than zero(positive integer) is called happy number, if we repeatedly replace the number, by sum of square of its digits till the final result becomes 1
Examples :

19 is a happy number 

12+92 = 82 
82+22 = 68
62+82 = 100
12+02+02 = 1

31 is a happy number 

32+12 = 10 
12+02 = 1

If the process loops endlessly in a cycle that does not include 1 then the number is called unhappy number or sad number.  In other words, those numbers which does not end in 1 in the above process are unhappy numbers or sad numbers.

Some of the examples of unhappy number are : 11 , 12 , 30

Happy numbers upto 100 are : 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100 
Happy Number Program in Java :
import java.util.Set;
import java.util.HashSet;
import java.util.Scanner;

public class HappyNumber {

public static void main(String args[]) {
System.out.println("Enter any number : ");
// Input the number
int inputNumber = new Scanner(System.in).nextInt();
Boolean result = isHappyNumber(inputNumber);
if (result == true)
System.out.print(inputNumber + " is a Happy number");
else
System.out.print(inputNumber + " is an Unhappy number");
}

public static boolean isHappyNumber(int number) {
Set<Integer> seenNumbers = new HashSet<Integer>();
while(seenNumbers.add(number)){
int digitsSum = 0;
while(number > 0) {
digitsSum += Math.pow(number % 10 , 2);
number /= 10;
}
number = digitsSum;
if(number == 1)
return true;
}
return false;
}
}


Output :

Enter any number : 86
86 is a Happy number 
Code Explanation :To check whether an input number is happy or not :

1. Calculate the square of each digit present in the inputNumber. Add it to a variable digitsSum.
  • If the resulting value of digitsSum is 1 then the input number is happy number.
  • Else the number is unhappy number.    
Points To Remember :1. According to Wikipedia, the happiness of a number remains unaffected by inserting or removing any number of zeros anywhere in the number and by rearranging the digits. 

2. The members of the sequence are happy, if the given number is happy. For example 7 is a happy number as shown below, so sequences 49, 97, 130, 10 are also happy numbers.

7 is a happy number as shown below

02+72 = 49 
42+92 = 97
92+72 = 130
12+32+02 = 10
12+02 = 1

Similarly, if a number is unhappy, then all of its sequence members are also unhappy numbers.

That's all for this post. Please mention in comments if you have any questions related to happy number program in java with examples.
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
The problem we are going to discuss here is about one of the scenarios where you have a self-executing JAR file having a Java application bundled inside it and you try executing it. When we are executing the JAR file, we need to point to a class with a main method ( public static void main(String[] args) which will be serving as the starting point for our application. This class is the one with the main method. In order to run the main method from our jar, we need to mention it inside the ‘Main-Class’ property of the manifest file (mainClass attribute in POM.xml in case of Mavenized application) which needs to be bundled with the code as well.

Problem:

no main manifest attribute, in "APPLICATION_NAME.jar"

For explanation purpose, we have an application named "Tutorial" with a class named Demo.java under com.javahungry package. Below are the content of the POM.xml and Demo.java file.


POM.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javahungry</groupId>
<artifactId>Tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Tutorial</name>
</project>


Demo.java

package com.javahungry; 
public class Demo {

public static void main(String args[]) 
    {
System.out.println(" Java Hungry ");
}
}

SolutionThis error occurs whenever Main-Class property is missing from manifest file MANIFEST.MF which can be found under META-INF folder in the jar.

Correct it by adding below lines to your pom.xml


<!-- include below build tag to your existing pom.xml  --> 
<build>
<plugins>
<plugin>

<!-- Building an executable jar -->

<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>

<!-- give full qualified name of your main class-->
<mainClass>com.javahungry.Demo</mainClass>

</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>


Let’s build the Tutorial application after adding the above changes in pom.xml.

Building the project in eclipse:

1. Running the application with below goal from Eclipse

Application Name -->  Right Click --> Run As --> Maven Install 

maven install 

or run below goal from command line

mvn install

This will create a jar file of the application (in this case Tutorial-0.0.1-SNAPSHOT.jar).

Execute the JAR:

2. We will now try executing this jar manually through command line and see what happens.

•    Open command prompt.
•    Go to the location of the jar file (usually set to application’s target folder in the Eclipse workspace).
•    Execute the command  java -jar .jar. See the example below.
 
java -jar Tutorial-0.0.1-SNAPSHOT.jar

The option -jar above only works when the JAR file is an executable JAR file. An executable JAR means JAR file must contain a manifest file with a Main-Class property in it.

If jar is not an executable JAR, then you need to run the program with below command

java -cp  Tutorial-0.0.1-SNAPSHOT.jar  com.javahungry.Demo

where com.javahungry.Demo is a class which contains main method to run the program.

Output :

Java Hungry

As you can see that the ‘no main manifest attribute’ related error has been resolved and our application has given us the expected output.

Fix no main manifest attribute, in jar Error in Spring BootAdd spring-boot-maven-plugin in build section of your pom.xml. If it is not added then add the below lines

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.5.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>


ExplanationAs we all know there must be an entry point to any java application and it must be a Java class containing the main method. In the problem we just discussed here, the manifest file was not having Main-Class property defined in it.

This property is responsible for indicating the Java class which main method (public static void main(String[] args)) needs to be executed. In other words, it tells Java about the starting point of the application.

Let us see what happens if we do not include the Main-Class property in manifest file of our project.
Current MANIFEST.MF file contains below content.

MANIFEST.MF
Manifest-Version: 1.0
Built-By: Subham Mittal
Build-Jdk: 1.8.0_91
Created-By: Maven Integration for Eclipse


1. Running the application with below goal from Eclipse


Application Name -->  Right Click --> Run As --> Maven Install

maven install 

or run below goal from command line

mvn install

This will create a jar file of the application (in this case Tutorial-0.0.1-SNAPSHOT.jar).

2. We will now try executing this jar manually through command line and see what happens.

Execute the JAR :

1.  Open command prompt.
2.  Go to the location of the jar file (usually set to application’s target folder in the Eclipse workspace).

Execute the command  java -jar .jar. See the example below. 

java -jar Tutorial-0.0.1-SNAPSHOT.jar

Output :

no main manifest attribute, in Tutorial-0.0.1-SNAPSHOT.jar


As we can deduce that this error has occurred because we did not define any starting point for the Tutorial application while creating the Tutorial-0.0.1-SNAPSHOT.jar file. The MANIFEST.MF file that was generated by default did not contain Main-Class property in this case.

Let’s have a look at the generated default manifest file.

MANIFEST.MF
Manifest-Version: 1.0
Built-By: Subham Mittal
Build-Jdk: 1.8.0_91
Created-By: Maven Integration for Eclipse

You can see Main-Class property is missing in the above MANIFEST.MF file.

To fix this issue, we have taken help of maven-jar-plugin which provides jar building capabilities. In the newer versions of this plugin like 3.1.2, we are supposed to define our own manifest file as “useDefaultManifestFile” parameter has been removed from the plugin configuration.

We added maven-jar-plugin in pom.xml with mainClass property inside it.

<mainClass>com.javahungry.Demo</mainClass>


MANIFEST.MF (after including maven-jar-plugin and mainClass property in the pom file):

Manifest-Version: 1.0
Built-By: Subham Mittal
Build-Jdk: 1.8.0_91
Created-By: Maven Integration for Eclipse
Main-Class: com.javahungry.Demo


Check out the highlighted "Main-Class" property that has been added to the manifest file after we have updated the pom file (refer Solution part). It indicates that the main method of com.javahungry.Demo class of our Tutorial  application will be executed. That's all for the post no main manifest attribute in jar error. Please mention in the comments if you are still facing the error or solve it by any other method.

References:
Default Manifest
Apache Maven jar plugin

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview