Likes

Thread in Java

Java & Threads


Threads are essentially subprocesses1. Informally, you can think of them as tasks that belong to a program and that can run "simultaneously". Depending on the number of CPUs available and the number of competing threads, some of those threads actually will run in parallel on different CPUs, whilst in other cases the illusion of simultaneous execution will be achieved by "juggling" threads in and out of the available CPUs. A part of the OS called the thread scheduler takes care of deciding which threads to allocate CPU time to (on which CPUs) and when.
Who needs to know about thread programming?
In the past, people who needed to know about thread programming were generally people writing applications that dealt with multiple "requests" or "jobs" concurrently, such as a web server or maybe a web browser making simultaneous requests to download a web page and associated images. But many other "client" or "desktop" applications didn't involve threads: there was generally only one CPU on a desktop machine, so everything was just done in one thread. Even games, which often needed to create the illusion of, say, different characters simultaneously moving about, would still use one thread and just "loop through" the various characters to move on every frame. (Look at pretty much any tutorial on game programming written until fairly recently, and the first chapter will inevitably be about "the game loop"...)
But increasingly, practically every programmer needs to know about threading and parallel programming. A fundamental characteristic of "game loop" approach is that it will only occupy one processor. The only way to improve performance with this approach (aside from using better algorithms) is to increase processor speed. This hasn't mattered until recently, because single processor speeds were continually increasing. But increased performance nowadays is being achieved via increased numbers of CPUs rather than increased speed of a single CPU. This means that to get our game or calculator program to perform better, we need to put the multiple CPUs to work in parallel. And by and large, that means multiple threads.

Getting started: what are threads, and how to use them in Java


It's easier to illustrate what a thread is by diving straight in and seeing some code. We're going to write a program that "splits itself" into two simultaneous tasks. One task is to print Hello, world! every second. The other task is to print Goodbye, cruel world! every two seconds. OK, it's a silly example.
For them to run simultaneously, each of these two tasks will run in a separate thread. To define a "task", we create an instance of Runnable. Then we will wrap each of these Runnables around a Thread object.
Runnable
A Runnable object defines an actual task that is to be executed. It doesn't define how it is to be executed (serial, two at a time, three at a time etc), but just what. We can define a Runnable as follows:
Runnable r = new Runnable() {
  public void run() {
    ... code to be executed ...
  }
};
Runnable is actually an interface, with the single run() method that we must provide. In our case, we want the Runnable.run() methods of our two tasks to print a message periodically. So here is what the code could look like:
Runnable r1 = new Runnable() {
  public void run() {
    try {
      while (true) {
        System.out.println("Hello, world!");
        Thread.sleep(1000L);
      }
    } catch (InterruptedException iex) {}
  }
};
Runnable r2 = new Runnable() {
  public void run() {
    try {
      while (true) {
        System.out.println("Goodbye, " +
               "cruel world!");
        Thread.sleep(2000L);
      }
    } catch (InterruptedException iex) {}
  }
};
For now, we'll gloss over a couple of issues, such as how the task ever stops. As you've probably gathered, the Thread.sleep() method essentially "pauses" for the given number of milliseconds, but could get "interrupted", hence the need to catch InterruptedException. We'll come back to this in more detail in the section on Thread interruption and InterruptedException. The most important point for now is that with the Runnable() interface, we're just definingwhat the two tasks are. We haven't actually set them running yet. And that's where the Thread class comes in...
Thread
A Java Thread object wraps around an actual thread of execution. It effectively defines how the task is to be executed— namely, at the same time as other threads2. To run the above two tasks simultaneously, we create a Thread object for each Runnable, then call the start() method on each Thread:
Thread thr1 = new Thread(r1);
Thread thr2 = new Thread(r2);
thr1.start();
thr2.start();
When we call start(), a new thread is spawned, which will begin executing the task that was assigned to the Thread object at some time in the near future. Meanwhile, control returns to the caller of start(), and we can start the second thread. Once that starts, we'll actually have at least three threads now running in parallel: the two we've just started, plus the "main" thread from which we created and started the two others. (In reality, the JVM will tend to have a few extra threads running for "housekeeping" tasks such as garbage collection, although they're essentially outside of our program's control.)

 

Difference between “implements Runnable” and “extends Thread” in java

Difference between “implements Runnable” and “extends Thread” in java
In java language, as we all know that there are two ways to create threads. One using Runnable interface and another by extending Thread class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class DemoRunnable implements Runnable {
    public void run() {
        //Code
    }
}
//with a "new Thread(demoRunnable).start()" call

public class DemoThread extends Thread {
    public DemoThread() {
        super("DemoThread");
    }
    public void run() {
        //Code
    }
}
//with a "demoThread.start()" call
There has been a good amount of debate on which is better way. Well, I also tried to find out and below is my learning:
1) Implementing Runnable is the preferred way to do it. Here, you’re not really specializing or modifying the thread’s behavior. You’re just giving the thread something to run. That means composition is the better way to go.
2) Java only supports single inheritance, so you can only extend one class.
3) Instantiating an interface gives a cleaner separation between your code and the implementation of threads.
4)  Implementing Runnable makes your class more flexible. If you extend thread then the action you’re doing is always going to be in a thread. However, if you extend Runnable it doesn’t have to be. You can run it in a thread, or pass it to some kind of executor service, or just pass it around as a task within a single threaded application.
5) By extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same runnable instance.
The issue is that at construction time, a Thread is added to a list of references in an internal thread table. It won’t get removed from that list until its start() method has completed. As long as that reference is there, it won’t get garbage collected.

 

 

 

 

Constructing Threads and Runnables

In our Java threading introduction, we created a thread in two steps:
  • firstly, we constructed a Runnable object to define the code to be executed by the thread;
  • then, we constructed a Thread object around the Runnable.
There are actually a couple of variations on this pattern of thread construction that we'll look at here.

Pattern 1: create an explicit class that implements Runnable

The Runnable implementations that we created were inline classes. That is, we didn't spell out a full class declaration. But strictly speaking, the way to create a Runnable— or rather, a class that implements the Runnable interface— is as follows:
public class MyTask implements Runnable {
  public void run() {
    ...
  }
}
...
Runnable r = new MyTask();
Thread thr = new Thread(r);
If we just write new Runnable(), the compiler under the hood actually creates a "dummy class" of the above form for us. But sometimes it's useful to create our own class. In our simultaneous message printing example, both Runnables essentially had similar code: only the message and time interval differed. So it would be neater to define a class that took the message and interval as parameters to the constructor:
public class MessagePrinter implements Runnable {
  private final String message;
  private final long interval;
  public MessagePrinter(String msg, long interval) {
    this.message = msg;
    this.interval = interval;
  }
  public void run() {
    try {
      while (true) {
        System.out.println(message);
        Thread.sleep(interval);
      }
    } catch (InterruptedException iex) {}
  }
}
Notice that for reasons we'll come to, we declare the variables final. This is basically a means of making sure they are "seen properly" by the two threads involved (the thread that constructs the object, then the thread in which run() will actually be running when we start the thread).

Pattern 2: override Thread.run()

You can actually dispense with the separate Runnable method. The Thread class has a (normally empty) run() method. If you don't pass in a Runnable to the constructor, then the run() method of Thread will be called instead when the thread starts. So we could write something like this:
public void MyThread extends Thread {
  public void run() {
    ...
  }
}
...
Thread thr = new MyThread();
thr.start();
Of course, we can also turn this into an inline class:
Thread thr = new Thread() {
  public void run() {
    ...
  }
}
thr.start();

Which thread construction pattern?

So, which method should you use to construct a thread in Java? In general, constructing a separate Runnable gives you more flexibility. Running in aThread turns out not to be the only way of running a Runnable, so if you embed everything inside a Thread object from the beginning, you may end up with more code to change later on if you decide to do things differently. In the simplest case, having a separate Runnable allows you to write code such as the following:
public void runTask(Runnable r, boolean separateThread) {
  if (separateThread) {
    (new Thread(r)).start();
  } else {
    r.run();
  }
}
Other instances where a Runnable is used are with the Swing.invokeLater() method (called from a non-Swing thread to ask Swing to run a particular task in its UI thread), or with various executor utilities introduced in the Java 5 concurrency package.
On the other hand, for threads representing fairly "major" tasks running right through your application, where it's clear from the ground up that you don't need the flexibility of the separate Runnable object, just overriding Thread.run() may make your code a little less cluttered.

Thread methods in Java


On the previous page, we looked at how to construct a thread in Java, via the Runnable and Thread objects. We mentioned that the Thread class providescontrol over threads. So on this page, we take a high-level look at the most important methods on this class.
Thread.sleep()
We actually saw a sneak preview of Thread.sleep() in our Java threading introduction. This static method asks the system to put the current thread to sleep for (approximately) the specified amount of time, effectively allowing us to implement a "pause". A thread can be interrupted from its sleep.
For more details, see: Thread.sleep() (separate page).
interrupt()
As mentioned, you can call a Thread object's interrupt() method to interrupt the corresponding thread if it is sleeping or waiting. The corresponding thread will "wake up" with an IOException at some point in the future. See thread interruption for more details.
setPriority() / getPriority()
Sets and queries some platform-specific priority assignment of the given thread. When calculating a priority value, it's good practice to always do so in relation to the constants Thread.MIN_PRIORITY, Thread.NORM_PRIORITY and Thread.MAX_PRIORITY. In practice, values go from 1 to 10, and map on to some machine-specific range of values: nice values in the case of Linux, and local thread priorities in the case of Windows. These are generally the range of values of "normal" user threads, and the OS will actually still run other threads beyond these values (so, for example, you can't preempt the mouse pointer thread by setting a thread to MAX_PRIORITY!).
Three main issues with thread priorities are that:
  • they don't always do what you might intuitively think they do;
  • their behaviour depends on the platform and Java version: e.g. in Linux, priorities don't work at all in Hotspot before Java 6, and the mapping of Java to OS priorities changed under Windows between Java 5 and Java 6;
  • in trying to use them for some purpose, you may actually interfere with more sensible scheduling decisions that the OS would have made anyway to achieve your purpose.
For more information, see the section on thread scheduling and the discussion on thread priorities, where the behaviour on different platforms is compared.
The join() method is called on the Thread object representing enother thread. It tells the current thread to wait for the other thread to complete. To wait for multiple threads at a time, you can use a CountDownLatch.
Thread.yield()
This method effectively tells the system that the current thread is "willing to relinquish the CPU". What it actually does is quite system-dependent. For more details, see: Thread.yield() (separate page).
setName() / getName()
Threads have a name attached to them. By default, Java will attach a fairly dull name such as Thread-12. But for debugging purposes you might want to attach a more meaningful name such as Animation Thread, WorkerThread-10 etc. (Some of the variants of the Thread constructor actually allow you to pass in a name from the start, but you can always change it later.)

Thread interruption in Java


In our overview of thread methods, we saw various methods that throw InterruptedException.
Interruption is a mechanism whereby a thread that is waiting (or sleeping) can be made to prematurely stop waiting.
Incidentally, it is important not to confuse thread interruption with either software interrupts (where the CPU automatically interrupts the current instruction flow in order to call a registered piece of code periodically— as in fact happens to drive the thread scheduler) and hardware interrupts (where the CPU automatically performs a similar task in response to some hardware signal).
To illustrate interruption, let's consider again a thread that prints a message periodically. After printing the message, it sleeps for a couple of seconds, then repeats the loop:
Runnable r = new Runnable() {
  public void run() {
    try {
      while (true) {
        Thread.sleep(2000L);
        System.out.println("Hello, world!");
      }
    } catch (InterruptionException iex) {
      System.err.println("Message printer interrupted");
    }
  }
};
Thread thr = new Thread(r);
thr.start();
The InterruptedException is thrown by the Thread.sleep() method, and in fact by a few other core library methods that can "block", principally:
  • Object.wait(), part of the wait/notify mechanism;
  • Thread.join(), that makes the current thread wait for another thread to complete;
  • Proess.waitFor(), which lets us wait for an external process (started from our Java application) to terminate;
  • various methods in the Java 5 concurrency libraries, such as the tryLock() method of the Java 5 ReentrantLock class.
In general, InterruptedException is thrown when another thread interrupts the thread calling the blocking method. The other thread interrupts the blocking/sleeping thread by calling interrupt() on it:
thr.interrupt();
Provided that the thread or task calling sleep() (or whatever) has been implemented properly, the interruption mechanism can therefore be used as a way to cancel tasks.

Stopping a thread

On the previous pages, we focussed on how to start a thread in Java. We saw that after creating the Thread object, calling start() asynchronously starts the corresponding thread. In our example, the run() method contained an infinite loop. But in real life, we generally want our thread to stop. So how do we make our thread stop?
Firstly, the thing you shouldn't do is call Thread.stop(). This method, now deprecated, was intended to stop a given thread abruptly. But the problem with this is that the caller can't generally determine whether or not the given thread is at a safe point to be stopped. (This isn't just a Java phenomenon: in general, the underlying operating system calls that Thread.stop() makes to abruptly stop the thread are also deprecated for this reason.)
So how can we stop a thread safely? In general:
To make the thread stop, we organise for the run() method to exit.
There are a couple of ways that we would typically do so.

Use a "stop request" variable

A common solution is to use an explicit "stop request" variable, which we check on each pass through the loop. This technique is suitable provided that we can check the variable frequently enough:
private volatile boolean stopRequested = false;
 
public void run() {
  while (!stopRequested) {
    ...
  }
}
 
public void requestStop() {
  stopRequested = true;
}
Note that we must declare the stopRequested variable as volatile, because it is accessed by different threads.

Use Thread.interrupt()

The above pattern is generally suitable if the variable stopRequested can be polled frequently. However, there is an obvious problem if the method blocksfor a long time, e.g. by calling Thread.sleep() or waiting on an object. In general, such blocking methods are interruptible. For more information, see the section on thread interruption.


How threads work: more details


In our introduction to Java threads, we showed the basics of how to start a thread, and the idea that threads let us run multiple tasks or "mini-programs" in parallel. But to understand certain thread programming issues in more detail, it's helpful to take a more detailed look at what threads actually are and how they work.
http://www.javamex.com/tutorials/threads/ThreadDiagram.png
Figure 1: Typical relationsip between
threads and processes.
Threads and processes
A thread is essentially a subdivision of a process, or "lightweight process" (LWP) on some systems. A process is generally the most major and separate unit of execution recognised by the OS. The typical relationship between processes, threads and various other elements of the OS are shown in Figure 1 opposite. This shows two processes, each split into two threads (a simplistic situation, of course: there will be typically dozens of processes, some with dozens or more threads).
Crucially, each process has its own memory space. When Process 1 accesses some given memory location, say 0x8000, that address will be mapped to some physical memory address1. But from Process 2, location 0x8000 will generally refer to a completely different portion of physical memory. Athread is a subdivision that shares the memory space of its parent process. So when either Thread 1 or Thread 2 of Process 1 accesses "memory address 0x8000", they will be referring to the same physical address. Threads belonging to a process usually share a few other key resources as well, such as their working directory, environment variables, file handles etc.
On the other hand, each thread has its own private stack and registers, including program counter. These are essentially the things that threads need in order to be independent. Depending on the OS, threads may have some other private resources too, such as thread-local storage(effectively, a way of referring to "variable number X", where each thread has its own private value of X). The OS will generally attach a bit of "housekeeping" information to each thread, such as its priority and state (running, waiting for I/O etc).
The thread scheduler
There are generally more threads than CPUs. Part of a multithreaded system is therefore a thread scheduler, responsible for sharing out the available CPUs in some way among the competing threads. Note that in practically all modern operating systems, the thread scheduler is part of the OS itself. So the OS actually "sees" our different threads and is responsible for the task of switching between them2. The rationale for handling threading "natively" in the OS is that the OS is likely to have the information to make threading efficient (such as knowing which threads are waiting for I/O and for how long), whereas a software library may not have this information available. In the rest of our discussion, we'll generally assume this native threads model.
Next: scheduling and its implications for Java
On the next pages, we look at


1. Things are usually a little more complex, in fact. For example, a memory address can actually be mapped to something that isn't memory (such as a portion of a file, or device I/O). For this reason, the term address space is often preferred.
2. An alternative scenario, less common nowadays, is that the OS schedules at some higher level, e.g. scheduling processes, or scheduling some kind of "kernal thread" which is a unit bigger than our applications threads. In this model, sometimes called "green threads", threads are to some extent "artificially" handled by the JVM (or the threading library that it is compiled against). In general, if you are using Java 1.4 onwards on Windows or on Solaris 9 or Linux kernel 2.6 or later, then there will be a 1:1 mapping between Java Threads and "native" operating system threads.

Thread Scheduling


In our introduction to how threads work, we introduced the thread scheduler, part of the OS (usually) that is responsible for sharing the available CPUs out between the various threads. How exactly the scheduler works depends on the individual platform, but various modern operating systems (notably Windows and Linux) use largely similar techniques that we'll describe here. We'll also mention some key varitions between the platforms.
Note that we'll continue to talk about a single thread scheduler. On multiprocessor systems, there is generally some kind of scheduler per processor, which then need to be coordinated in some way. (On some systems, switching on different processors is staggered to avoid contention on shared scheduling tables.) Unless otherwise specified, we'll use the term thread scheduler to refer to this overall system of coordinated per-CPU schedulers.
Across platforms, thread scheduling1 tends to be based on at least the following criteria:
  • a priority, or in fact usually multiple "priority" settings that we'll discuss below;
  • a quantum, or number of allocated timeslices of CPU, which essentially determines the amount of CPU time a thread is allotted before it is forced to yield the CPU to another thread of the same or lower priority (the system will keep track of the remaining quantum at any given time, plus its defaultquantum, which could depend on thread type and/or system configuration);
  • a state, notably "runnable" vs "waiting";
  • metrics about the behaviour of threads, such as recent CPU usage or the time since it last ran (i.e. had a share of CPU), or the fact that it has "just received an event it was waiting for".
Most systems use what we might dub priority-based round-robin scheduling to some extent. The general principles are:
  • a thread of higher priority (which is a function of base and local priorities) will preempt a thread of lower priority;
  • otherwise, threads of equal priority will essentially take turns at getting an allocated slice or quantum of CPU;
  • there are a few extra "tweaks" to make things work.
States
Depending on the system, there are various states that a thread can be in. Probably the two most interesting are:
  • runnable, which essentially means "ready to consume CPU"; being runnable is generally the minimum requirement for a thread to actually be scheduled on to a CPU;
  • waiting, meaning that the thread currently cannot continue as it is waiting for a resource such as a lock or I/O, for memory to be paged in, for a signal from another thread, or simply for a period of time to elapse (sleep).
Other states include terminated, which means the thread's code has finished running but not all of the thread's resources have been cleared up, and a newstate, in which the thread has been created, but not all resources necessary for it to be runnable have been created. Internally, the OS may distinguish between various different types of wait states2 (for example "waiting for a signal" vs "waiting for the stack to be paged in"), but this level of granularity is generally not available or so important to Java programs. (On the other hand, Java generally exposes to the programmer things the JVM can reasonly know about, for example, if a thread is waiting to acquire the lock on a Java object— roughly speaking, "entering a synchronized block".)

ASP MT Solved

Ques1 Conside a scenario where you are trying to directky deploy a web application on the IIS server of your development computer.As the first step Internet Information Services(IIS) Manager and currently accessing the Add Apllication dialog box.At this stage which of the following information (ch11)

1.A name of the application,A URL to access the application
2.The pysical path where the website will be saves,A URL to access the application
3.An Alias name of the application,The physical path where the application will be saved
4.The URL to access IIS,The physical path where the website will be saved.


================================
Ques2 When you execute the application,the application is automatically deployed on____.
(ch11)
=====================
Ques3 DatePicker Code(ch8)
====================
Ques4 Create CSS file code(ch6)
===============
Ques5 The IEnumarable interface is avaible in the ____ namespaces.(ch6)
===============
Ques6 Range Data Annotation(ch4)
=====================
Ques7 To implement client-side validation in an MVC application,which one of the follwing options is not required?
1.Add annotation to the model class
2.use HTML validation helpers in Razor view to display error message
3.Include the jQuery validation script
4.Add custom error message to annotation in model class
=========================
Ques8 Which of the follwing statements is true regarding the ReadOnly attribute applied to a property? (ch 4)
1.Ensures that the property is not made availble to the view
2.Specifies constraints for a numeric value entered by the user
3.Ensures that the default model binder will not set the property with a new value from the request
4.Helps you provide information about the specific purpose of a property at runtime
=========================
Ques9 In server-side validation,if the model state contains an error,the ____property retuns false
1.ModelState.IsValid
2.ModelState.Valid
3.ModelState.IsError
4.ModelState.IsInValid
=========================
Ques10 Which one of the following code snippet will generate a URL of the Login action in the Account controller?
1.@HTMl.ActionLink("Login","Action")
2.@Url.ActionLink("Login","Action")
3.MvcHtmlString.ActionLink("Login","Action")
4.@Url.Action("Login","Account")
=====================
Ques11 RadioButton coding(from book Topic Helper Method)
====================
Ques12 The _____ helper method is used to display an editor for the specified model property.
================
Ques13 Custom Route(Go through the Animation)

Identify the URL that cannot match with the following
===================
Ques14 What wll be the result when the following URL is sent to an MVC application through a Web browser?
http://newbay.com/Index/RegistrationController
=====================
Ques15 Chris is given an existing ASP.NET MVC application created by using scaffolding feature.In the application,he has to make changes to the HTMl template.Which options?
1.Views folder
2.Web config file
3.App_Data folder
4.Controller folder
=======================
Ques16 You have created a controller for a web apllication with the name Tutorial.What will be the name of the folder created by default under the Views folder if you use the scallofding
1.Tutorial
2.TutorialController
3.Home
4.Controller
=============================
Ques17 FadeIn() and FadeOut() methods of JavaScript coding
=========================

Sem4 MT6


1.Define the following terms:

Purchase Order
Delivery Challan
Rejection Note
Goods Received Note
Goods Inwards Note
Ans:
i)Purchase Order - A document from the customer to the seller listing the required items and providing a description of the goods.
ii)Delivery Challan - A document that is sent with the shipment of goods. It lists the description, and quantity of the goods that are delivered.
iii)Rejection Note - A document that lists the materials that are rejected due to defects found during quality inspection. The reason of rejection is also included.
iv)Goods Received Note - A document that acknowledges that the materials have been inspected and accepted by the manufacturer.
v)Goods Inwards Note - A document that records the entries of the materials when they are received at the store of the organization.

2.Identify the various criteria for classifying an organization and discuss them in detail.

Ans:
An organization consists of a group of people working specifically to achieve a common goal. Organizations can be classified on the basis of nature of work, profitability, type of system, and ownership

i)Based on the Nature of Work:
Organizations can be classified depending on their nature of work as:

a)Manufacturing-based: Business organizations involved in producing tangible goods or products are called manufacturing organizations. b)Automobile manufacturing companies, iron and steel plants, and food and beverage processing units are examples of manufacturing organizations.
c)Service-based: Business organizations involved in providing services to other businesses or people, rather than producing tangible goods, are called service-based organizations. Airlines, hotels, hospitals, banks, and insurance agencies are examples of service organizations.
Based on Profitability:

ii)Organizations may be classified on the basis of their focus on profit. These organizations can be:

a)Profit-based organizations: The primary goal of these organizations is to increase their profit margin. These organizations try to increase the value of their share by increasing the value of the company stock.
b)Nonprofit-based organizations: These organizations do not have profit as their primary goal. They are usually involved with socially relevant issues. Some examples of nonprofit organizations include social groups, universities, human rights commissions, and worker unions.

iii)Based on the Type of System:
Based on the type of system an organization implements, it can be classified as simple or complex and adaptive or nonadaptive.

a)Simple or complex: A simple system consists of a lesser number of elements that interact with each other in a simple and uncomplicated manner. An eating joint is an example of a simple system, wherein the customer places an order, the ordered food is prepared, and the food is served to the customer.  Components in a complex system have a high level of interaction with each other. A car manufacturing organization is an example of a complex system.
b)Adaptive or nonadaptive: An adaptive organization is one that is able to change in response to the changes in the environment. For example, the fashion and cosmetics industries are highly dependent on external stimuli. A nonadaptive organization is one that is not able to change easily in response to external stimuli. For example, the automobile industry needs to take many factors into account before deciding on a change. These factors may include the cost of manufacturing a modified product or the availability of raw materials.

iv)Based on Ownership:
On the basis of the nature of ownership, business organizations can be classified into the following types:

a)Sole proprietorship: When one individual heads a business organization, it is said to be sole proprietorship.
b)Partnership: A partnership organization has two or more individuals conducting the business together. Corporation: A corporation is a legal entity conducting business with numerous owners.

3.Explain the following terms briefly:Test caseCollaborationGeneralizationJob shopsBatch processing

Ans:
i)Test case: A test case is a set of actions that is executed to examine whether or not the implemented code of the software system complies with the requirements stated by the customer. This helps you to validate the system functionality against system requirements. A test case developed for a particular function of the software system includes a set of test input, execution conditions, and expected results.
ii)Collaboration: UML provides specific modeling constructs, known as collaborations, to model a use case realization in the design phase. Collaboration is a collection of classes, interfaces, and sub-systems that interact with each other to achieve the functions of a use case. It can be represented by creating an oval with a dotted line.
iii)Generalization: The generalization relationship exists among the actors or use cases that have similar behavior and properties. Two actors or use cases are said to have a generalization relationship when the characteristics of one actor or use case can be derived from the characteristics of another actor or use case.
iv)Job shops: The Job shop production process involves the manufacturing of a wide variety of products in small numbers for a specific customer requirement. This production process is used to make a higher number of products as compared to projects. Job shops require general-purpose equipment that is flexible, because every product goes through a different sequence of processes. In job shops, resources are sometimes overloaded, while at other times, they may be idle. Examples of a job shop include manufacturing of special items, such as furniture.
v)Batch processing: The batch processing production process involves large-scale manufacturing of products on the same equipment. Every new product incurs additional setup costs that can be reduced by manufacturing more units in each cycle. Products are stocked and supplied based on customer demand. Batch processing caters to those products that are generic in nature. Therefore, general-purpose equipment is used. The process does not undergo many changes, but skilled workers are required to perform tasks. Examples of batch processing include book publishing, garment manufacturing, and pharmaceutical production.

4.Describe the class diagram and class notations used in UML. Explain the visibility of attributes and operations in a class diagram. Explain the syntax of attributes and operations in class diagrams.

Ans:
Class diagram and class notations used in UML

A class diagram is used to create a structural model of a software system. The structural model describes the static architecture of a system and helps the software developer to translate the system use cases into system design.

 UML provides a class notation to represent classes in class diagrams. The class notation has three compartments where the first compartment depicts the name of the class, the second compartment depicts the attributes of the class, and the third compartment depicts the operations of the class.You can use class notations to document the design of a system in accordance with the requirements identified during the requirements analysis phase.
Visibility of attributes and operations

It is vital to ensure that the data of your classes remain secure. For this, UML allows you to specify the visibility of the class attributes and operations, which controls the accessibility of these class members from other classes. UML provides the following four visibilities for the attributes and operations of a class:

i)+: Indicates that the attribute or operation is accessible to other classes. In other words, the attribute or operation is public.
ii)-: Indicates that the attribute or operation is inaccessible to other classes. In other words, the attribute or operation is private.
iii)#: Indicates that the attribute or operation in the base class is accessible to derived classes. In other words, the attribute or operation is protected.
iv)~: Indicates that the attribute or operation is accessible to the classes, which are within the same package.
Syntax of attributes in class diagrams

The attributes of a class follow certain syntax in the class diagrams. The syntax to depict an attribute in a class diagram is:

visibility name: type

The preceding syntax contains the following mandatory fields:

i)visibility: Specifies whether the attribute of the class is private, public, protected, or package.
ii)name: Indicates the name of the attribute. This is a mandatory field.
iii)type: This is an optional field. It specifies the data type of the attribute.
For example, the Name attribute of the Employee class can be represented as:

-Name: String

Syntax of operations in class diagrams

The syntax to represent an operation of a class in the class diagrams is:

visibility name (parameter-list): return-type

The preceding syntax contains the following fields:

i)visibility: Specifies whether the operation of the class is private, public, protected, or package.
ii)name: Indicates the name of the operation.
iii)parameter-list: Indicates the list of parameters for the operat.
iv)return-type: Represents the data type of the value returned by the operation. This field can take the null value when the operation does not return any value.
The parameters of an operation are denoted using the following syntax:

Parameter name: type

For example, the getName() operation of the Employee class can be represented as:

+getName(EmpId : int) : string

5.What is meant by logistics? Explain the activities involved in logistics planning (any two) in detail.

Ans:
Logistics is a business-planning framework. It involves planning for the movement and storage of materials and information from any point in the operational process to the final order-fulfillment stage. Organizations thrive on the effectiveness and efficiency of their operational strategies. An efficient logistics plan supports in implementing the organizational processes, such as production and sales and marketing, effectively.

Logistics planning involves the following activities:

Analyzing the core business processes

Analysis of the core business processes of an organization is important as the logistics activities differ depending on the nature of the business undertaken by an organization.

Some of the general processes for a typical manufacturing-based business organization include:

i)Purchasing of material
ii)Receiving the material
iii)Warehousing
iv)Controlling the inventory
v)Handling the material
vi)Shipping
vii)Making decisions for physical distribution

The distribution of products is an important activity for an organization and its customers. For example, in a manufacturing organization, the goods are typically moved from the Production department to the warehouses, where they are stored until they are sent to the dealers.
The main factors to be considered while making decisions for the physical distribution are:

The size, number, and location of warehouses
The mode of transport depending on the type of goods, distances, and weights
The work force to be employed or hired.
Deciding the location of facilities:

Whenever an organization wants a new factory, warehouse, shop, office or other facilities, it is important to identify a strategic location.

Most organizations evaluate the feasibility of the location of a facility, such as a production plant, based on the factors, such as:

i)The locations of competitors, suppliers, and customers
ii)Availability of skilled workforce in the area
iii)Costs pertaining to operations, wages, transport, and taxes
iv)Transport and services availability
v)Plans regarding future expansion, or globalization

6.What is a state machine diagram? Explain its various components.

Ans:
Before developing a software system, a developer must understand the various states through which a component goes from its creation to termination. For this, UML provides a state machine diagram. A state machine diagram represents the various states that an object goes through during its lifecycle in response to events. You need to model the behavioral aspects of a system by using state diagrams. Therefore, you create a state diagram for the objects that respond to events. The various constituents of a state diagram are states, events, and transitions.

i)A state depicts a condition of an object and the activities of an object during its lifecycle. An initial state is the starting state of an object and is represented as a dot. A final state is the end state of an object and is represented as a dot encircled by a ring.
ii)An event is an occurrence that triggers a change of state of an object. It signifies the receipt of a message that requests for an operation to be performed.
iii)A transition is a change of state of an object due to the occurrence of an event. For example, the state of customer complaint transitions from Open to Closed when the Complaint Resolved on Phone event occurs. Similarly, the state transitions from Open to Waiting when the Complaint Not Resolved on Phone event occurs and from Waiting to Closed when the Complaint Resolved Onsite event occurs.

7.What is a product? Explain the product life cycle in detail.

Ans:
A product is an article or a substance that is manufactured or produced by a company for sale. The main objective of a product is to make the customer feel satisfied or benefited after the purchase of the product. Before marketing a product, it is important to understand the life cycle of a product in the market. When a product is launched, the demand for it varies with time. There are different stages through which the product passes when it is introduced in the market. These stages comprise the product life cycle. The life cycle of a product starts when it is launched in the market till the time it remains in the market. This life cycle helps organizations in analyzing the product's impact on the organization's market share. The different stages of a product life cycle are: introduction, growth, maturity, and decline.

i)Introduction: This is the first stage when the product is introduced in the market. The main focus of the organization at this stage is to make the customer aware of the product and its benefits. For this, organizations invest more in advertising and other promotional strategies. The focus is not on revenue generation.
ii)Growth: At the growth stage, once the product is established in the market, more retailers and customers are attracted to it. At this stage, the organization maintains the quality and price of the product to attract more customers. This results in profits for the organization.
iii)Maturity: At the maturity stage, the sale of the product first reaches saturation in the market. The distribution of the product reaches to the fullest in the market, leaving minimum demand for the product. Thereafter, its sale starts declining. The primary goals of an organization at this stage are to maintain the market share and promote the product by differentiating it from competitors? product.
iv)Decline: At the decline stage, there is a rapid increase of competing products that may be better in quality and low in price. As a result, sales start declining and production volumes need to be reduced. The primary goal of an organization at this stage is to try maintaining the sale of the product by adding new features and reducing the cost. However, if the product is still incurring loss, the organization may discontinue the product.

8.What is meant by logistics? Explain the activities involved in logistics planning (any two) in detail.

Ans:
Logistics is a business-planning framework. It involves planning for the movement and storage of materials and information from any point in the operational process to the final order-fulfillment stage. Organizations thrive on the effectiveness and efficiency of their operational strategies. An efficient logistics plan supports in implementing the organizational processes, such as production and sales and marketing, effectively.

Logistics planning involves the following activities:

i)Analyzing the core business processes

ii)Analysis of the core business processes of an organization is important as the logistics activities differ depending on the nature of the business undertaken by an organization.

Some of the general processes for a typical manufacturing-based business organization include:

i)Purchasing of material
ii)Receiving the material
iii)Warehousing
iv)Controlling the inventory
v)Handling the material
vi)Shipping
vii)Making decisions for physical distribution

The distribution of products is an important activity for an organization and its customers. For example, in a manufacturing organization, the goods are typically moved from the Production department to the warehouses, where they are stored until they are sent to the dealers.
The main factors to be considered while making decisions for the physical distribution are:

i)The size, number, and location of warehouses
ii)The mode of transport depending on the type of goods, distances, and weights
iii)The work force to be employed or hired.
Deciding the location of facilities:

Whenever an organization wants a new factory, warehouse, shop, office or other facilities, it is important to identify a strategic location.

Most organizations evaluate the feasibility of the location of a facility, such as a production plant, based on the factors, such as:

i)The locations of competitors, suppliers, and customers
ii)Availability of skilled workforce in the area
iii)Costs pertaining to operations, wages, transport, and taxes
iv)Transport and services availability
v)Plans regarding future expansion, or globalization

9.Explain the various stages of marketing process.

Ans:
The stages of the marketing process are analyzing the need for a product, deciding upon the marketing strategy, implementing the marketing strategy, and monitoring the product.

i)Analyzing the need for a product: While analyzing the need for a product, organizations need to analyze the customer's requirements and its own capabilities to manufacture a product. While planning for the marketing strategy for a product, an organization must analyze whether it has sufficient funds to be able to manufacture and get sufficient returns.
ii)Deciding upon the marketing strategy: After the analysis of the customer requirements and market trends, an organization needs to decide upon its marketing strategy. This strategy requires a decision on the marketing mix as well as a target market for which the marketing mix is prepared. The marketing mix consists of variables that marketing managers can control in order to best satisfy customers in the target market.
iii)Implementing a marketing strategy: The plan prepared at the decision stage of the marketing process is implemented at this stage. The product is launched in the market and the planned promotional strategies are implemented to ensure customer awareness and sale of the product. The launch of a product includes the following activities:
a)Product performance is evaluated through tests and quality checks.
b)Final packaging is designed and ordered.
c)Sales channels are identified and established.
d)Product feedback is updated based on market feedback and analysis.
e)Product documentation is completed and finalized.
f)User documentation, operating manuals, advertisement materials, product brochures, marketing materials, press releases, website pages, and maintenance instructions are completed and ready to be distributed at the appropriate time.
g)A Production Readiness Review document is prepared. This document confirms that all preparations are completed and the product is ready for launch.
h)The new product is launched when the service, sales, and distribution channels are ready.
iv)Monitoring the product: The task of the marketing team does not get over with the launch of the product in the market. At this stage, an organization needs to collect regular feedback from customers regarding their likes, dislikes, and suggestions for improvement of the product.  At this stage, competitors and their similar products need to be monitored closely and the marketing strategy may need to be modified accordingly.

10.What is structural modeling? List any three UML diagrams for structural modeling and explain them briefly.

Ans
UML provides various modeling techniques to represent the framework of a software system. Each modeling technique contains a set of diagrams to represent the requirements and structure of the software system. The UML modeling techniques may be used for structural modeling and behavioral modeling. Structural modeling involves depicting the static features of the software system. It is used to represent how the components or elements exist in a system.

The various UML diagram for structural modeling are:

i)Class diagram: A class diagram represents a set of classes, interfaces, and their relationships. It describes the set of attributes and operations associated with each class and the relationships among the various classes.
ii)Object diagram: An object diagram represents an instance of a class diagram. It represents the properties of a particular instance of a class.
iii)Package diagram: A package diagram represents the interrelated classes and interfaces of the system in a package.  It helps in representing the various packages of a software system and the dependencies between them. It also gives a high-level impression of use case and class diagrams.
iv)Component diagram: A Component diagram combines packages or individual entities to form components. You can depict these components and their dependencies by using a component diagram.
v)Deployment diagram: A deployment diagram shows the physical placement of components in nodes over a network. A deployment diagram can be drawn by identifying nodes and components.

11.Explain the concept of production planning in brief. Discuss in detail about the MRP phase of production planning.

Ans:
Production planning is an integral part of the production process. It is the first step in the production process. Every manufacturing-based organization performs a set of operations for producing finished goods. Each operation in the production process of an organization must be systematically designed, planned, organized, and controlled.

Production planning:

i)Helps organizations to develop and implement strategies so that cost-effective goods are produced with minimum resources.
ii)Involves the systematic scheduling of workers, materials, and machines for manufacturing products efficiently, economically, and timely.

The different phases of production planning are:
1. Material requirement planning (MRP)
2. Selecting the production process

MRP is an inventory control process used to calculate the amount of raw materials required to manufacture a specific product. MRP involves reviewing the stock quantity of raw materials according to the quantity of products to be manufactured in a specific period. It then involves calculating the quantity of components and materials required to manufacture those items and identifying the supply of materials required for the scheduled production. MRP involves planning work orders and purchase requisitions and suggesting appropriate rescheduling of the current material plan by taking into account the actual delivery date of a product.
The main inputs of MRP are:
i)Master Production Schedule (MPS) shows the quantity of products to be manufactured in a specific period. It is a detailed manufacturing plan that determines the products a manufacturer has to produce within predefined timelines. During MRP, the estimated plan provided by MPS is translated into a detailed plan that specifies the schedule for material requirement and delivery.
ii)Bill of Materials (BOM) consists of the materials, parts, and components that are required to manufacture the product. During MRP, the BOM and MPS are used to calculate the amount of each material required.
The lead-time is the time between the placement of an order for a product and the actual date of delivery. Determining lead-time of raw materials is essential for a manufacturing company so that the finished goods can be delivered to the customer in a timely manner and any shortages can be handled before the production process starts.
iii)Inventory records provide a detailed list of all the items that are currently in stock. The information is stored in a tabular format. MRP uses these existing inventory records to calculate the net quantity of materials required from the supplier. The net quantity required is calculated by subtracting the existing inventory from the total materials required as per MPS.
The main outputs of MRP are:
i)Schedule for Orders: It provides guidelines to place an order depending on the lead-time.
ii)Purchase Orders: It is a buyer's document and is used to formalize a purchase transaction with a supplier. On acceptance by the supplier, it becomes a legally binding contract between the two parties and hence, it must specify all terms and conditions applicable to the contract.
iii)Reports: The information from MRP is processed to generate various reports, such as performance reports and inventory transactions.