Explaining Concurrency In Java English Language Essay

Published:

This essay has been submitted by a student. This is not an example of the work written by our professional essay writers.

In java programming language has been designed and support concurrent programming, and all execution in the java takes place in the context of thread. It is very important to understanding java programmer the power and limits of java threads.

In the Java Virtual Machine (JVM), objects and resources can be accessed by many separate threads; each thread has its own path of execution but can potentially access any objects in this programming.

The developer should ensure that thirds do not interfere with each other, that resources are properly synchronized during both access (read and write). The java language has built-in-constructs to support coordination.

The java platform is designed for the ground up to support programming, which basic concurrency support in the java programming language and the java class libraries. Since java 5.0 include high-level concurrency APIs. The basic concurrency support and summarizes some of the high-level APIs in the

The concurrency utilizes packages provides a powerful, extensible framework of high- performance threading utilities such as third pool and block queues.

This package frees the programmers from the need to craft these utility by hand.

java.util.concurrent Packages

java.util.concurrent.atomic Package

java.util.concurrent.locks Package

java.util.concurrent Packages description

Utility classes commonly useful in concurrent programming. This package include a few small standardized extensible frameworks, as well as some classes that provide useful functionality and are otherwise tedious or difficult to implement.

java.util.concurrent.atomic Package description

A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, array elements to that also provide an atomic conditional update operation of the form:

Boolean compareAndSet(expectedValue, updateValue);

This method (which varies in arguments types across different classes) atomically sets a variable to the updateValue if it currently holds the expectedValue, reporting true on success. This package also contains methods to get and unconditionally set values, as well as a weaker conditional update weakCompareAnsSet. The weal version may be more efficient in the normal case, but differs in that any given invocation of weakCompareAndSet method may fail, even spuriously. A false return means only that the operation may be retried, relying on the guarantee that repeated invocation when the variable holds expectedValue and no other thread is also attempting to set the variable will eventually succeed.

The memory effects for accesses and update of atomics generally following the rules for volatiles:

Get has the memory effects of reading a volatile variable.

Set has the memory effects of writing (assigning) a volatile variable.

weakCompareAndSet atomically reads and conditionally writes a variable, is ordered with respect with respect to other memory operations on that variable, but otherwise acts as an ordinary non-volatile memory operation.

compareAndSet and all other read-and-update operations such as getAndIncrements have the memory effects of both reading and writing volatile variables.

java.util.concurrent.locks Package description:

Interface and classes providing a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors. The framework permits much greater flexibility in the use of locks and conditions, at the expense of more awkward syntax.

Exercise 2.

2.1

The Task

Using the essay developed in Exercise 1 as a reference point, explain how the different aspects of concurrent

programming may be implemented in JAVA. In particular, you should provide examples of those aspects together

with a detailed explanation of each.

2.2.

Deliverables

An essay of a maximum of 1500 words.

2.3.

Marking

Marks will be awarded for accuracy and completeness, up to a maximum of 70.

import java.io.IOException;

import java.io.PrintStream;

import java.util.Date;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.*;

public class ScheduleTester {

public static void main(String[] args) {

// Get the scheduler

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

// Get a handle, starting now, with a 10 second delay

final ScheduledFuture<?> timeHandle =

scheduler.scheduleAtFixedRate(new TimePrinter(System.out), 0, 10, SECONDS);

// Schedule the event, and run for 1 hour (60 * 60 seconds)

scheduler.schedule(new Runnable() {

public void run() {

timeHandle.cancel(false);

}

}, 60*60, SECONDS);

/**

* On some platforms, you'll have to setup this infinite loop to see output

while (true) { }

*/

}

}

class TimePrinter implements Runnable {

private PrintStream out;

public TimePrinter(PrintStream out) {

this.out = out;

}

public void run() {

out.printf("Current time: %tr%n", new Date());

}

}

Explanation:

Package explanation:

1.Java.io.Exception,here we are importing this package because in this class file we are using PrintStream this class throws IOException.this IOException is a checked Exception or compile time exception so we have to handle it using try ,catch block or dug it using thows key word.this ioexception is coming from the hirarche of OuputStream and FilterOutputStream.

2. Java.io.PrintStream it adds other functionality to other stream class,it ables to print all sort of data values from various data conveniently. PrintStream is used to flush automatically, this means that the flush method is automatically invoked after a byte array is written.

The constructors supported by PrintStream:

PrintStream(File f)

Takes file as argument.

PrintStream(File f, String s)

Which takes File and String as arguments, the string is charset specification.

PrintStream(OutputStream out, boolean autoFlush)

Create a new print stream.

PrintStream(OutputStream out, boolean autoFlush, String encoding)

Create a new print stream.

PrintStream(String fileName)

Creates a new print stream, without automatic line flushing, with the specified file name.

PrintStream(String fileName, String csn)

Creates a new print stream, without automatic line flushing, with the specified file name and charset.

Using the methods in PrintStream class we do our manuplation on our program the methods are appened(), close(), flush(),format(), print(),println(), write().

Java.util.Date, using this date class we can print the current date in our program, we can get current system time and we can do our manipulation in our code.

Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 Ã- 60 Ã- 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction

Constructors in Date Class

Date()

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

Date(long date)

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

The methods that we can use from the Date Class are after(), before(), getDate(), getDay(), getHours(), getMinitues(), getSeconds(), getMonth(),getyear(),getTime(),toGMTString()

java.util.concurrent.Executors

Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. This class supports the following kinds of methods:

* Methods that create and return an ExecutorService set up with commonly useful configuration settings.

* Methods that create and return a ScheduledExecutorService set up with commonly useful configuration settings.

* Methods that create and return a "wrapped" ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible.

* Methods that create and return a ThreadFactory that sets newly created threads to a known state.

* Methods that create and return a Callable out of other closure-like forms, so they can be used in execution methods requiring Callable.

java.util.concurrent.ScheduledExecutorService

public interface ScheduledExecutorService

The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically until cancelled.

All schedule methods accept relative delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a Date to the required form. For example, to schedule at a certain future date, you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS). Beware however that expiration of a relative delay need not coincide with the current Date at which the task is enabled due to network time synchronization protocols, clock drift, or other factors. The Executors class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package.

java.util.concurrent.ScheduledFuture

This scheduleFuture interface is a result for ScheduledExecutorService

static java.util.concurrent.TimeUnit

public enum TimeUnit is a enumeration, enum is one of type same like a class type, it is used to define range based constants values, the keyword enum specifies the definition of the enumeration. enums will not have any constructors like class, enum values can be public, static and final.enum values can be compared with equals method and ==, enum overrides toString().

declartionof enum

public enum Grade { A, B, C, D, F, INCOMPLETE };

A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts.

Methods in Timeunit

convert(long duration, TimeUnit unit)

Convert the given time duration in the given unit to this unit.

toNanos(long duration)

Equivalent to NANOSECONDS.convert(duration, this).

toMicros(long duration)

Equivalent to MICROSECONDS.convert(duration, this).

timedWait(Object obj, long timeout)

Perform a timed Object.wait using this time unit.

values()

Returns an array containing the constants of this enum type, in the order they're declared.

Key words in this program:

Import: it is one of reserved key word I java, which is used to import the other classes where this class is using. Using import we can import any no of classes and you can use all the classes.

Class: class is also reserved key word in java, is one type in java with this we can define a class and we can create object , where a object can state and behavior .state is nothing but member variables and behavior is methods.

New:new is also one reserved key word in java, using this new we can create object for any class which is non-abstract class, after creating the new object for a class we can access all the instance variables and instance methods. We cannot access instance variables and instance methods with out creating object for the class.when we create object for the class the default constructor will be invoked of that class.if you write the default zero parameterized constructor for a class the JVM will not provide you the default constructor. If you don’t write any constructor in your class, the jvm will provide you the default constructor as a zero parameterized constructor.

Public:public is the one the access modifiers in java, the other access modifiers are private,protected.public access modifiers can be applicable to class , member variables and methods.if use public for a class, that class can be used any where in the application.public gives universal access to all the resources that are in the application.if you are writing the public to the methods those methods can be access in all other classes , where this class has used.

Private: private is another access modifiers. Private can be applied to only to methods and variables we cannot write for a class. For a class we can write only one access modifier i.e., public, the other one is by not writing any one (public, private, protected), it is a default access. If you write private to the member variables and to the methods tey can be accessible with in that class only, we cannot access outside the class.

Static: static is non-access modifiers in java, we can write this static to member variables, methods. By writing the static to the member variables, methods will get access without creating any object to that class, means if we have static things declared in class, to access that static thing s we no need to create object for that class. the static things will load along with the class, so the decision about the static things will be taken at compile time. The instance things decision will be taken at runtime.

Main: the main is the main method name, if class is having the main method then that class is said to be executable class.

Void: void means the main method doesn’t return anything. the main method itself is static method so all the static things can directly use in the main method.

Writing Services

Essay Writing
Service

Find out how the very best essay writing service can help you accomplish more and achieve higher marks today.

Assignment Writing Service

From complicated assignments to tricky tasks, our experts can tackle virtually any question thrown at them.

Dissertation Writing Service

A dissertation (also known as a thesis or research project) is probably the most important piece of work for any student! From full dissertations to individual chapters, we’re on hand to support you.

Coursework Writing Service

Our expert qualified writers can help you get your coursework right first time, every time.

Dissertation Proposal Service

The first step to completing a dissertation is to create a proposal that talks about what you wish to do. Our experts can design suitable methodologies - perfect to help you get started with a dissertation.

Report Writing
Service

Reports for any audience. Perfectly structured, professionally written, and tailored to suit your exact requirements.

Essay Skeleton Answer Service

If you’re just looking for some help to get started on an essay, our outline service provides you with a perfect essay plan.

Marking & Proofreading Service

Not sure if your work is hitting the mark? Struggling to get feedback from your lecturer? Our premium marking service was created just for you - get the feedback you deserve now.

Exam Revision
Service

Exams can be one of the most stressful experiences you’ll ever have! Revision is key, and we’re here to help. With custom created revision notes and exam answers, you’ll never feel underprepared again.