Showing posts with label java examples. Show all posts
Showing posts with label java examples. Show all posts

Wednesday, 24 May 2023

Java ExcecutorService Example

The Java ExecutorService is an interface that provides a way to execute tasks asynchronously. It is part of the java.util.concurrent package.

The ExecutorService interface provides a number of methods for submitting tasks, retrieving results, and managing the pool of threads. Some of the most commonly used methods are:

  • submit(Runnable task): Submits a task to the executor service. The task will be executed by one of the threads in the pool.
  • submit(Callable task): Submits a task to the executor service. The task will be executed by one of the threads in the pool and the result will be returned.
  • invokeAll(Collection tasks): Executes all of the tasks in the collection and returns a list of Futures. A Future represents the result of a task.
  • invokeAny(Collection tasks): Executes all of the tasks in the collection and returns the result of the first task that completes.
  • shutdown(): Shuts down the executor service. No new tasks will be accepted after the executor service has been shut down.
  • shutdownNow(): Shuts down the executor service and attempts to cancel all of the running tasks.

The ExecutorService interface can be used to execute a variety of tasks, such as:

  • Parsing a large file
  • Rendering a complex image
  • Executing a database query
  • Sending an email

The ExecutorService interface provides a convenient way to execute tasks asynchronously. It can help to improve the performance of your application by allowing you to execute multiple tasks at the same time.

Here is an example of how to use the ExecutorService interface to execute a task:

Code snippet
ExecutorService executorService = Executors.newFixedThreadPool(10);

Runnable task = () -> {
  // Do something
};

Future<String> future = executorService.submit(task);

String result = future.get();

In this example, we create an ExecutorService with a fixed pool of 10 threads. We then submit a task to the executor service. The task will be executed by one of the threads in the pool and the result will be returned. We can then get the result of the task by calling the get() method on the Future object.

The ExecutorService interface is a powerful tool that can be used to execute tasks asynchronously. It can help to improve the performance of your application by allowing you to execute multiple tasks at the same time.

Saturday, 3 January 2015

Java Data Types

Data types in Java can be broadly classified in two categories

1. Primitive data types / Simple data types
2. Non-primitive data types / Derived data types or Referenced data types

Primitive Data Types

Although java is an object oriented language, but the primitive data types are not objects. They are kept in java for performance reason. They form the basis for all other types of data that you define in your java programs.

The primitive data types may be further classified as:

1. Numeric data types

-- Integer data types - byte, short, int, long
-- Floating data types - float, double

2. Boolean data type - boolean

3. Character data type - char

Reference Data Types

Reference are also called derived data types as they are derived from the primitive data types. Reference data types can be further classified as:

1. Classes
   Built-in / Library classes
   User-Defined classes

2. Interfaces
   Built-in / Library classes
   User-Defined classes

3. Arrays

Array are treated as objects in Java, which is different from C++.

Java Separators

The Java separators are more or less same as C/C++ separators.

;          Semicolon
,          Comma
.          Period
[]         Square Brackets
()         Parenthesis
{}        Braces

Sunday, 21 December 2014

Java source file structure

All java source files must end with the extension ".java". A source file may contain at the most one top level public class. If a public class is present, the un-extended file name should be same as the class name i.e. if the class name is Hello then the source file name should be Hello.java. If a source file does not contain any public class then name of the source file can be anything.

A source file may contain an unlimited number of non-public class definitions.

There are four top level elements that may appear in a file. None of these elements is must. If they are present, then they must appear in the following order:

  1. Package definitions
  2. import statements
  3. class and/or interface definitions
A source file may have at the most one package statement. If a package statement is present it must be the first statement in the java program. Only comments may appear before the package statements.

A source file may have zero or more import statements. As of now you can think of import statements to be like #include statements in the Java Program. If present, all the import statements must come after the package statement and before the class/interface definitions.

A source file may have any number of class and/or interface definitions but there can be at the most one public class or interface.

main() method

A source file may or may not contain a class having main() method but a standalone java program always starts its execution from main() just like a C/C++ program. So the class from which we want to start the execution  must have the main() defined in it.

The main() method must always have the following signature:

public static void main(String args[])

Note: Method prototype is referred to as signature in Java.

The void keyword preceding main() method indicates that it does not return any value. The keyword public indicates that the main method can be accessed from anywhere. The main() method must be declared public as it is called by the code, which is part of the JVM and is outside the class containing the main() method.

The main() method takes one argument, which is the array of strings. Each element of the array represents one command line argument.

The main() method can also be invoked like any other static method form anywhere in the java program. It can also be overloaded like any other Java method.

It is very common to get an exception indicating that the main() method is not present while running a java program event when the main() method is present. This happens when the signature of the main() method differs from the above mentioned signature.

Comments

A program can be documented by inserting comments wherever required. The comments are simply ignored by the compiler.

Java provides three types of comments for documentation:
  1. Single line comment
  2. Multi line comment
  3. Documentation comment
Single line Comment






A single line comment spans only one line. It can be given on any line followed by the character "//". The syntax is similar to C++.

Example

// This line is a comment and will be ignored by the compiler
x = 4*y // This is also a comment but appears after assignment statement

Multi line Comment

The syntax of multi line comment is same as C/C++. A multi line comment  is enclosed between "/*" and "*/".



Set Jdk path

If you install the JDK in folder c:\jdk\bin Type the command below:

SET PATH=%PATH%;C:\JDK\BIN;

Saturday, 20 December 2014

Running a Java Application

When a program is compiled (C or C++ program), it is directly translated into machine code that is specific to a platform/processor. But running a java program is a two-step process. In java translation from source code to the executable code is achieved using two translators:

Java Compiler: A java program is first compiled by the java compiler to generate bytecode. Bytecode resemble machine code but it is not specific to any platform i.e. it can not be executed on a computer without further translation.


Java Interpreter: Java interpreter executes the byte code after interpreting and converting into machine code.

Example: the following java program just displays the message "Hello World" on the monitor/console.

Step1: Write the following code into file "Hello.java" using any text editor:

public class Hello{
    public static void main(String args[]){
        System.out.println("Hello World");
    }
}

Note: Java is a case sensitive language


Step 2: Compile the above written java program using the command:
javac Hello.java

Step 3: Run the java program
java Hello


Output: Hello World