Thursday, March 12, 2020

Print Even and Odd number in the sequence by two threads in java


Print Even and Odd number in the sequence by two threads in java

Thread-1 1
Thread-0 2
Thread-1 3
Thread-0 4
Thread-1 5
Thread-0 6
Thread-1 7
Thread-0 8
Thread-1 9
Thread-0 10 


Printing this sequence is the coordination between the threads and this coordination can be achieved with the the help of wait and notify.

Two threads are running simultaneously.
When one thread enters the critical section then it checks whether odd is printed or not on the basis of the flag. If the odd in not printed then it waits for other thread to print the odd number and wait for notify signal and vice versa.

PrintEvenOddTester.java

public class PrintEvenOddTester {

      public static void main(String[] args) {
            Printer p = new Printer();

            TaskEvenOdd te1 = new TaskEvenOdd(10, ptrue);
            TaskEvenOdd te2 = new TaskEvenOdd(10, pfalse);

            Thread t1 = new Thread(te1);
            Thread t2 = new Thread(te2);

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

      }

}

TaskEvenOdd.java

public class TaskEvenOdd implements Runnable {

      private int max;
      private Printer print;
      private boolean isEvenNumber;

         public TaskEvenOdd(int max, Printer printboolean isEvenNumber) {
            this.max = max;
            this.print = print;
            this.isEvenNumber = isEvenNumber;
      }

      @Override
      public void run() {
            int number = isEvenNumber == true ? 2 : 1;
            while (number <= max) {
                  if (isEvenNumber) {
                        try {
                              print.printEven(number);
                        } catch (InterruptedException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                        }
                  } else {
                        try {
                              print.printOdd(number);
                        } catch (InterruptedException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                        }
                  }
                  number = number + 2;
            }

      }

}



Printer.java

public class Printer {
      boolean printOdd = false;

      public void printEven(int nthrows InterruptedException {
            synchronized (this) {

                  while (!printOdd) {
                        wait();
                  }

       System.out.println(Thread.currentThread().getName() + " " + n);
                  printOdd=false;
                  notifyAll();
            }
      }

      public void printOdd(int nthrows InterruptedException {
            synchronized (this) {
                  while (printOdd) {
                        wait();
                  }
       System.out.println(Thread.currentThread().getName() + " " + n);
                  printOdd=true;
                  notifyAll();

            }
      }

}

Output:
Thread-1 1
Thread-0 2
Thread-1 3
Thread-0 4
Thread-1 5
Thread-0 6
Thread-1 7
Thread-0 8
Thread-1 9
Thread-0 10 
===============================================


Method 2:



Create a class named "OddEvenRunnable".
It will implement the Runnable interface.
public class OddEvenRunnable implements Runnable{
 public int PRINT_NUMBERS_UPTO=10;
 static int  number=1;
 int remainder;
 static Object lock=new Object();
 OddEvenRunnable(int remainder)
 {
  this.remainder=remainder;
 }
 @Override
 public void run() {
  while (number < PRINT_NUMBERS_UPTO) {
   synchronized (lock) {
    while (number % 2 != remainder) { // wait for numbers other than remainder
     try {
      lock.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
    System.out.println(Thread.currentThread().getName() + " " + number);
    number++;
    lock.notifyAll();
   }
  }
 }
}

Create Main class named “PrintOddEvenMain”



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class PrintOddEvenMain {
 public static void main(String[] args) {
  OddEvenRunnable oddRunnable=new OddEvenRunnable(1);
  OddEvenRunnable evenRunnable=new OddEvenRunnable(0);
  Thread t1=new Thread(oddRunnable,"Odd");
  Thread t2=new Thread(evenRunnable,"Even");
 
  t1.start();
  t2.start();
 }
}


Output:

Odd 1
Even 2
Odd 3
Even 4
Odd 5
Even 6
Odd 7
Even 8
Odd 9
Even 10

================================================



Tuesday, March 3, 2020

PermGen and Metaspace



PermGen and Metaspace

PermGen is an abbreviation for Permanent Generation and it’s a special heap space which is separate from the main Java heap where JVM keeps track of metadata of the classes which have been loaded.

 In Java 8, PermGen has been renamed to Metaspace - with some subtle differences. From our perspective, it is important to note that Metaspace has an unlimited default maximum size.
On the contrary, PermGen from Java 7 and earlier has a default maximum size of 64 MB on 32-bit JVM and 82 MB on the 64-bit version. Of course, these are not the same as the initial sizes.
 Java 7 and earlier starts with something around 12-21 MB of the initial PermGen space.

JVM
Default maximum PermGen size (MB)
Default maximum Metaspace size
32-bit client JVM
64
unlimited
32-bit server JVM
64
unlimited
64-bit JVM
82
unlimited
It is worthwhile to mention that prior to Java 7, interned Strings used to be kept on the PermGen. That caused some serious problems with the infamous:
java.lang.OutOfMemoryError: PermGen space
Whenever there is a need to resize PermGen/Metaspace, JVM will do it as it does with the standard heap. Resizing those spaces requires a full GC, which is always an expensive operation. It can usually be observed during a startup when a lot of classes are being loaded. Especially if the application has dependencies on many external libraries. If there are a lot of full GCs during the startup, it’s usually because of that. If that case, increasing the initial size can boost the startup performance.
To increase PermGen, we have the following commands:
-XX:PermSize=N -  sets the initial (and minimum size) of the Permanent Generation space.
-XX:MaxPermSize=N  -  sets the maximum size of the Permanent Generation space.
In Java 8 and onwards, we can set the initial and maximum size of Metaspace using the following commands:
-XX:MetaspaceSize=N  - sets the initial (and minimum size) of the Metaspace.
-XX:MaxMetaspaceSize=N  - sets the maximum size of the Metaspace.

Examples:

java.lang.OutOfMemoryError: PermGen space
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)

1. Solution

By default, Tomcat is assigned a very little PermGen memory for the running process. To fix it, increase the PermGen memory settings by using the following Java VM options.
-XX:PermSize<size> - Set initial PermGen Size.
-XX:MaxPermSize<size> - Set the maximum PermGen Size.

2. Windows

Tomcat is managed by this script file catalina.bat, dive inside the script, you will find out that catalina.bat always find and run the setenv.bat file to set the environment variables.
{$tomcat-folder}\bin\catalina.bat
//...
rem Get standard environment variables
if not exist "%CATALINA_BASE%\bin\setenv.bat" goto checkSetenvHome
call "%CATALINA_BASE%\bin\setenv.bat"
goto setenvDone
:checkSetenvHome
if exist "%CATALINA_HOME%\bin\setenv.bat" call "%CATALINA_HOME%\bin\setenv.bat"
:setenvDone
//...
Copy
2.1 To set the environment variable on Windows, create a setenv.bat manually, and put it into the ${tomcat-folder}\bin folder.
${tomcat-folder}\bin\setenv.bat
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
Copy
P.S No double quotes, set JAVA_OPTS={value}.
2.2 Restart Tomcat, it will call the setenv.bat file to set the environment variable automatically.
{$tomcat-folder}\bin\catalina.bat restart
Copy

3. Linux

On Linux, the process is same, just Tomcat is using catalina.sh and setenv.sh instead.
3.1 Find out where is catalina.sh :
catalina.sh
$ sudo find / -name "catalina.sh"
Password:
find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory
/Users/mkyong/Downloads/apache-tomcat-6.0.35/bin/catalina.sh
Copy
3.2 Review the catalina.sh, script, it behaves like Windows, but use setenv.sh instead.
//...
# Ensure that any user defined CLASSPATH variables are not used on startup,
# but allow them to be specified in setenv.sh, in rare case when it is needed.
CLASSPATH=
 
if [ -r "$CATALINA_BASE/bin/setenv.sh" ]; then
  . "$CATALINA_BASE/bin/setenv.sh"
elif [ -r "$CATALINA_HOME/bin/setenv.sh" ]; then
  . "$CATALINA_HOME/bin/setenv.sh"
fi
//...
Copy
3.3 Create a setenv.sh manually, and put it into the ${tomcat-folder}\bin\ folder.
${tomcat-folder}\bin\setenv.sh
export JAVA_OPTS="-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m"
Copy
P.S With double quotes, export JAVA_OPTS=”{value}”.
3.4 Restart Tomcat.



Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > ...

Followers

Search This Blog

Popular Posts