Wednesday, 6 May 2009

5-How to Develop Container-Managed-Persistence Entity Beans

MySQL DDL, WLST Data source definition commands, WebLogic system config.xml files.

SCRIPT MySQL DDL for the orders table in the ‘testars’ database
create table orders (order_id varchar(64),
student_id varchar(64),
order_date Date,
status varchar(64),
amount DOUBLE PRECISION(12,2));

SCRIPT WLST Data Source definition commands
edit()
# Change these names as necessary
dsname="myJDBCDataSource"
server="DefaultServer"
cd("Servers/"+server)
target=cmo
cd("../..")
startEdit()
# start creation
print 'Creating JDBCSystemResource with name '+dsname
jdbcSR = create(dsname,"JDBCSystemResource")
theJDBCResource = jdbcSR.getJDBCResource()
theJDBCResource.setName("myJDBCDataSource")

connectionPoolParams = theJDBCResource.getJDBCConnectionPoolParams()
connectionPoolParams.setConnectionReserveTimeoutSeconds(25)
connectionPoolParams.setMaxCapacity(100)
connectionPoolParams.setTestTableName("SYSTABLES")
dsParams = theJDBCResource.getJDBCDataSourceParams()
dsParams.addJNDIName("styejbDB")

driverParams = theJDBCResource.getJDBCDriverParams()
driverParams.setUrl("jdbc:mysql://localhost:3306/testars")
driverParams.setDriverName("com.mysql.jdbc.Driver")

# driverParams.setUrl("jdbc:oracle:thin:@my-oracle-server:my-oracle-server-port:my-oracle-sid")
# driverParams.setDriverName("oracle.jdbc.driver.OracleDriver")
driverParams.setPassword("3391309")
# driverParams.setLoginDelaySeconds(60)
driverProperties = driverParams.getProperties()
proper0 = driverProperties.createProperty("user")
#proper.setName("user")
proper0.setValue("root")
proper1 = driverProperties.createProperty("DatabaseName")
#proper1.setName("DatabaseName")
proper1.setValue("jdbc:mysql://localhost:3306/testars")
jdbcSR.addTarget(target)
save()
activate(block="true")
print 'Done configuring the data source'

FILE WebLogic Default Server config file at C:\oracle\Middleware\jdeveloper\system\system11.1.1.0.31.51.88\DefaultDomain\config
The above script places it at the very bottom otomatically as:

<jdbc-system-resource>
<name>myJDBCDataSource</name>
<target>DefaultServer</target>
<descriptor-file-name>jdbc/myJDBCDataSource-9572-jdbc.xml</descriptor-file-name>
</jdbc-system-resource>
</domain>

And creates the related XXX-jdbc.xml file at
C:\oracle\Middleware\jdeveloper\system\system11.1.1.0.31.51.88\DefaultDomain\config\jdbc

FILE myJDBCDataSource-9572-jdbc.xml
<?xml version='1.0' encoding='UTF-8'?>
<jdbc-data-source xmlns="http://www.bea.com/ns/weblogic/jdbc-data-source" xmlns:sec="http://www.bea.com/ns/weblogic/90/security" xmlns:wls="http://www.bea.com/ns/weblogic/90/security/wls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/jdbc-data-source http://www.bea.com/ns/weblogic/jdbc-data-source/1.0/jdbc-data-source.xsd">
<name>myJDBCDataSource</name>
<jdbc-driver-params>
<url>jdbc:mysql://localhost:3306/testars</url>
<driver-name>com.mysql.jdbc.Driver</driver-name>
<properties>
<property>
<name>user</name>
<value>root</value>
</property>
<property>
<name>DatabaseName</name>
<value>jdbc:mysql://localhost:3306/testars</value>
</property>
</properties>
<password-encrypted>{3DES}K0c09YjvYiI=</password-encrypted>
</jdbc-driver-params>
<jdbc-connection-pool-params>
<max-capacity>100</max-capacity>
<connection-reserve-timeout-seconds>25</connection-reserve-timeout-seconds>
<test-table-name>SYSTABLES</test-table-name>
</jdbc-connection-pool-params>
<jdbc-data-source-params>
<jndi-name>styejbDB</jndi-name>
</jdbc-data-source-params>
</jdbc-data-source>

4-How to Develop Container-Managed-Persistence Entity Beans

Deployment Descriptors

FILE ejb-jar.xml
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC
'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>OrderARSEJB</ejb-name>
<home>cmpex.OrderARSHome</home>
<remote>cmpex.OrderARS</remote>
<ejb-class>cmpex.OrderARSEJB</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>OrderARS</abstract-schema-name>
<cmp-field>
<field-name>orderId</field-name>
</cmp-field>
<cmp-field>
<field-name>studentId</field-name>
</cmp-field>
<cmp-field>
<field-name>orderDate</field-name>
</cmp-field>
<cmp-field>
<field-name>status</field-name>
</cmp-field>
<cmp-field>
<field-name>amount</field-name>
</cmp-field>
<primkey-field>orderId</primkey-field>
<query>
<query-method>
<method-name>findByStatus</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>
<![CDATA[SELECT OBJECT(o) FROM OrderARS AS o
WHERE o.status = ?1]]>
</ejb-ql>
</query>
<query>
<query-method>
<method-name>ejbSelectAllOrderAmounts</method-name>
<method-params>
</method-params>
</query-method>
<ejb-ql>
<![CDATA[SELECT o.amount FROM OrderARS AS o
WHERE o.orderId IS NOT NULL]]>
</ejb-ql>
</query>
</entity>
</enterprise-beans>
</ejb-jar>

FILE weblogic-ejb.jar
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB//EN'
'http://www.bea.com/servers/wls700/dtd/weblogic-ejb-jar.dtd'>

<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>OrderARSEJB</ejb-name>
<entity-descriptor>

<persistence>
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>6.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
</persistence-use>
</persistence>

</entity-descriptor>
<jndi-name>cmpex/OrderARS</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>

FILE weblogic-rdbms-jar.xml
<!DOCTYPE weblogic-rdbms-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB RDBMS Persistence//EN'
'http://www.bea.com/servers/wls700/dtd/weblogic-rdbms20-persistence-700.dtd'>
<weblogic-rdbms-jar>
<weblogic-rdbms-bean>
<ejb-name>OrderARSEJB</ejb-name>
<data-source-name>styejbDB</data-source-name>
<table-map>
<table-name>orders</table-name>
<field-map>
<cmp-field>orderId</cmp-field>
<dbms-column>order_id</dbms-column>
</field-map>
<field-map>
<cmp-field>studentId</cmp-field>
<dbms-column>student_id</dbms-column>
</field-map>
<field-map>
<cmp-field>orderDate</cmp-field>
<dbms-column>order_date</dbms-column>
</field-map>
<field-map>
<cmp-field>status</cmp-field>
<dbms-column>status</dbms-column>
</field-map>
<field-map>
<cmp-field>amount</cmp-field>
<dbms-column>amount</dbms-column>
</field-map>
</table-map>
</weblogic-rdbms-bean>
</weblogic-rdbms-jar>

3-How to Develop Container-Managed-Persistence Entity Beans

Client

FILE Client.java
import cmpex.*;
import java.util.*;
import javax.naming.*;
import javax.ejb.*;

public class Client {
public static void main(String[] args) {
print("Starting Client . . .\n");
Context initialContext = null;
OrderARSHome orderHome = null;
OrderARS order = null;
try {
print("Looking up the order home via JNDI.\n");
initialContext = new InitialContext();
Object object = initialContext.lookup("cmpex/OrderARS");
orderHome =
(OrderARSHome)javax.rmi.PortableRemoteObject.narrow(object,
OrderARSHome.class);
order = (OrderARS)orderHome.create("1", "Submitted", 100);
String orderId = order.getOrderId();
print("Created a new order:" + orderId + " .\n");
print("Locating the order " + orderId +
" using findByPrimaryKey method.\n");

order = orderHome.findByPrimaryKey(orderId);
print("Locating all orders with status Submitted " +
" using findByStatus method.\n");
Collection col = orderHome.findByStatus("Submitted");
Enumeration orders = Collections.enumeration(col);

while (orders.hasMoreElements()) {
order = (OrderARS)orders.nextElement();
print("Order id:" + order.getOrderId());
}

print("Finding the total amount of all orders using \n" +
" getTotalAmountOfAllOrders home method.\n");
double totalAmount = orderHome.getTotalAmountOfAllOrders();
print("Total amount:" + totalAmount);
} catch (Exception e) {
e.printStackTrace();
}
}

static void print(String s) {
System.out.println(s);
}
}

2-How to Develop Container-Managed-Persistence Entity Beans

CMP Entity Bean files:

FILE: OrderARSHome.java
package cmpex;

import java.util.*;
import java.rmi.*;
import javax.ejb.*;

public interface OrderARSHome extends EJBHome {
/* Create methods */
public OrderARS create(String studentId,
String status, double amount) throws CreateException, RemoteException;
/* Finder methods */
public OrderARS findByPrimaryKey(String key)
throws FinderException, RemoteException;
public Collection findByStatus(String status)
throws FinderException, RemoteException;
/* Home methods */
public double getTotalAmountOfAllOrders()
throws FinderException, RemoteException;
}

FILE OrderARS.java
package cmpex;

import java.rmi.*;
import javax.ejb.*;

public interface OrderARS extends EJBObject {
public String getOrderId()
throws RemoteException;
public String getStudentId()
throws RemoteException;
public void setStudentId(String studentId)
throws RemoteException;
public double getAmount()
throws RemoteException;
public void setAmount(double amount)
throws RemoteException;
public java.sql.Timestamp getOrderDate()
throws RemoteException;
public void setOrderDate(java.sql.Timestamp date)
throws RemoteException;
public String getStatus()
throws RemoteException;
public void setStatus(String status)
throws RemoteException;
}

FILE OrderARSEJB.java
package cmpex;

import java.util.*;
import java.io.*;
import java.rmi.*;
import javax.naming.*;
import javax.ejb.*;

public abstract class OrderARSEJB implements EntityBean
{
protected EntityContext ctx;
public abstract String getOrderId();
public abstract void setOrderId(String orderId);
public abstract String getStudentId();
public abstract void setStudentId(String studentid);
public abstract java.sql.Timestamp getOrderDate();
public abstract void setOrderDate(java.sql.Timestamp timestamp);
public abstract String getStatus();
public abstract void setStatus(String status);
public abstract double getAmount();
public abstract void setAmount(double amount);
/* Callback methods */
public void setEntityContext(EntityContext ctx) {
print("setEntityContext called");
this.ctx = ctx;
}
public void unsetEntityContext() {
print("unsetEntityContext called.\n");
this.ctx = null;
}
public void ejbActivate() {
print("ejbActivate() called.\n");
}
public void ejbPassivate() {
print("ejbPassivate() called.\n");
}
public void ejbStore() {
print("ejbStore() called.\n");
}
public void ejbLoad() {
print("ejbLoad() called.\n");
}
public void ejbRemove() throws RemoveException {
print("ejbRemove() called.\n");
}
public String ejbCreate( String studentId,
String status, double amount) throws CreateException {
print("ejbCreate() called.\n");
String orderId = getUniqueId();
setOrderId(orderId);
setStudentId(studentId);
setStatus(status);
setAmount(amount);
setOrderDate(new java.sql.Timestamp(System.currentTimeMillis()));
return null;
}
public void ejbPostCreate(String studentId,
String courseId, double amount) throws CreateException {
print("ejbPostCreate() called.\n");
}
/* Home methods */
public double ejbHomeGetTotalAmountOfAllOrders()
throws FinderException {
double totalAmount = 0.0;
Collection col = ejbSelectAllOrderAmounts();
Enumeration amounts=Collections.enumeration(col);
while( amounts.hasMoreElements() ) {
Double amount= (Double)amounts.nextElement();
totalAmount += amount.doubleValue();
}
return totalAmount;
}
/* select methods. */
public abstract Collection ejbSelectAllOrderAmounts()
throws FinderException ;

void print(String s) {
System.out.println(s);
}
String getUniqueId(){
return new Long(System.currentTimeMillis()).toString();
}
}

1-How to Develop Container-Managed-Persistence Entity Beans

This article is about how I managed to build CMP Entity Beans using the Developing Container-Managed Persistence Entity Beans example of tinptB ‘s Blog: EJB in 21 Days: http://ejbvn.wordpress.com/
I appreciate her excellent English, which makes a soothing effect while trying to break through difficulties.

The difference of my work to TINPTB’s is first my work is complete and contains everything necessary to work.
TINPTB’s mission is more about teaching EJB’s thus she concentrates on providing the concise source necessary for creating them. He also provides necessary deployment descriptor scripts for both WebLogic and JBOSS. At this point her work begins to get questionable due to the different versions etc…

My solution works on Jdeveloper 11g(only the client not the deployment), WebLogic10.3, wlfullclient5, apache-ant-1.7.1 and mysql-essential-5.1.30-win32, mysql-connector-java-5.0.8 and Toad for MySQL 4.1 Freeware.

The first difficulty I had was the name used namely order is actually considered a key word by WebLogic 10.3,
Thus I had to change the CMP Entity Bean to XXXARS, ARS being the initials of my name.

Second, TINPTB does not need tomention that there has to be a jndi.properties file somewhere. He may be using the WebLogic console or some other tool instead…???

1- I created/copied the OrderXXX files as given in EJB in 21 Days. I had to change the library name(cmpex).
I also put the ejb-jar.xml, weblogic-ejb-jar.xml, weblogic-cmp-rdbms-jar.xml files into src/META-INF directory. I put the Client.java and jndi.properties also in the src directory. So, the directory structure is:
BMPex
src
Bmpex ..........................META-INF ...........Client.java ......jndi.properties
OrderHomeARS.java ....ejb-jar.xml
OrderARS.java ..............weblogic-ejb-jar.xml
OrderARSEJB.java .......weblogic-cmp-rdbms-jar.xml

At the same level with src lies:
Lib Build Deploy build.xml
wlfullclient5.jar

But also, in your weblogic domain’s lib directory, by the way I use DefaultServer;
C:\oracle\Middleware\jdeveloper\system\system11.1.1.0.31.51.88\DefaultDomain\lib
should include
mysql-connector-java-5.0.8-bin

2- I changes all names ‘order’ to ‘orderARS’. I changed ‘ch11’ lib names to ‘cmpex’. Most important,
There is a small discrepancy in the definition of
<weblogic-rdbms-jar>
<weblogic-rdbms-bean>
<ejb-name>OrderARSEJB</ejb-name>
<data-source-name>styejbDB</data-source-name>
If I give data-source-name above it asks for the JNDI name. So, I entered the JNDI name there.
3- I deployed with WLST as my WebLogic console does not work (or exist at all for some mysterious reason).

connect('weblogic','weblogic','t3://localhost:7101')

deploy("CMPent","C:/CMPentity/deploy/CMPent.jar" "DefaultServer",securityModel="Advanced", block="true")

Here, the library CMPEntity is the place where I used a build.xml file with Ant to compile and create the CMPent.jar. I also used ANT RUN command to run the client here. You may find this build file towards the end of this BLOG entries series.

If something goes wrong about the data source definition or ejb’s make sure that the JNDI tree has corresponding entries. For that, you can use
help(‘trees’)
jndi()
help(‘jndi’)
and so on…

Tuesday, 5 May 2009

5-A SIMPLE PROCESS SIMULATION

V. This example introduces randomnes to the weights of JobTasks directly. As in:
class JobTask4 extends Thread {
public int taskWeight = 1+(int)(400*Math.random());
With this, both the duration and the starting times of JobTasks become random.
package stochasticprocess;

public class JobQueue5 {

private final static int NUMRUNNERS = 10;

public JobQueue5() {
}
public static void main(String[] args) {
JobTask5[] runners = new JobTask5[NUMRUNNERS];

// for (int i = 0; i < NUMRUNNERS; i++) {
// runners[i] = new JobTask5(i);
// runners[i].setPriority(2);
// }
//
// for (int i = 0; i < NUMRUNNERS; i++)
// runners[i].start();

MonitorTask5 monitorTask5 = new MonitorTask5(999, runners);
monitorTask5.setPriority(1);
monitorTask5.start();

DispatcherTask5 dispatcherTask5 = new DispatcherTask5(111, runners);
dispatcherTask5.setPriority(1);
dispatcherTask5.start();

}
}

class JobTask5 extends Thread {
public int taskWeight = 1+(int)(400*Math.random());
public int taskWeightCounter = 1;
private int taskId;

public JobTask5(int taskId) {
this.taskId = taskId;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
System.out.println("Job Task Thread #" + taskId + ", remaining taskWeight = " + (taskWeight - taskWeightCounter));
}
}
}
class MonitorTask5 extends Thread {
private int taskWeight = 2000;
public int taskWeightCounter = 1;
private int taskId;
JobTask5[] runningTasks;
int sumRunningTasks;
int taskLoadLimit=300;

public MonitorTask5(int taskId, JobTask5[] runnerTasks) {
this.taskId = taskId;
this.runningTasks = runnerTasks;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;
try {
sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
{
sumRunningTasks = 0;
for(int i=0; i < runningTasks.length; i++){
if (runningTasks[i] != null)
sumRunningTasks += runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter;
}
System.out.print("==========================================>");
System.out.println("Monitor Task Thread total Running Job taskWeight =" + sumRunningTasks);
System.out.println("Monitor Task Thread #" + taskId + ", remaining taskWeight = " + (taskWeight - taskWeightCounter));
if (sumRunningTasks > taskLoadLimit){
System.out.print("++++++++++++++++++++++++++++++++++++++++++++++>");
System.out.println("Task Load limit " + taskLoadLimit + "is exceeded by " + (sumRunningTasks - taskLoadLimit ));
}
}
}
}
}
class DispatcherTask5 extends Thread {
public int taskWeight = 600;
public int taskWeightCounter = 1;
private int taskId;
JobTask5[] runningTasks;

public DispatcherTask5(int taskId, JobTask5[] runnerTasks) {
this.taskId = taskId;
this.runningTasks = runnerTasks;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10+(int)(100*Math.random()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
{
for (int i = 0; i < runningTasks.length; i++) {
if (runningTasks[i] != null) {
if ((runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter) == 0) {
System.out.println("Dispatcher Task Thread dispatches new JobTaskkkkkkkkkkkkkkkkkkkkkkkkkkkk Thread #" + i);
runningTasks[i] = new JobTask5(i);
runningTasks[i].setPriority(2);
runningTasks[i].start();
break;
}
}
else {
runningTasks[i] = new JobTask5(i);
runningTasks[i].setPriority(2);
runningTasks[i].start();
}
}
System.out.println("Dispatcher Task Thread #" + taskId + ", remaining taskWeight = " + (taskWeight - taskWeightCounter));
}
}
}
}

4-A SIMPLE PROCESS SIMULATION

This example introduces randomness to the JobTasks by changing the sleep time of the dispatcher:

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10+(int)(100*Math.random()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

It also arranges MonitorTask’s weight to 2000.

package stochasticprocess;

public class JobQueue4 {

private final static int NUMRUNNERS = 10;

public JobQueue4() {
}
public static void main(String[] args) {
JobTask4[] runners = new JobTask4[NUMRUNNERS];

// for (int i = 0; i < NUMRUNNERS; i++) {
// runners[i] = new JobTask4(i);
// runners[i].setPriority(2);
// }
//
// for (int i = 0; i < NUMRUNNERS; i++)
// runners[i].start();

MonitorTask4 monitorTask4 = new MonitorTask4(999, runners);
monitorTask4.setPriority(1);
monitorTask4.start();

DispatcherTask4 dispatcherTask4 = new DispatcherTask4(111, runners);
dispatcherTask4.setPriority(1);
dispatcherTask4.start();

}
}

class JobTask4 extends Thread {
public int taskWeight = 1+(int)(400*Math.random());
public int taskWeightCounter = 1;
private int taskId;

public JobTask4(int taskId) {
this.taskId = taskId;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
System.out.println("Job Task Thread #" + taskId + ", remaining taskWeight = " + (taskWeight - taskWeightCounter));
}
}
}
class MonitorTask4 extends Thread {
private int taskWeight = 2000;
public int taskWeightCounter = 1;
private int taskId;
JobTask4[] runningTasks;
int sumRunningTasks;
int taskLoadLimit=300;

public MonitorTask4(int taskId, JobTask4[] runnerTasks) {
this.taskId = taskId;
this.runningTasks = runnerTasks;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;
try {
sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
{
sumRunningTasks = 0;
for(int i=0; i < runningTasks.length; i++){
if (runningTasks[i] != null)
sumRunningTasks += runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter;
}
System.out.print("==========================================>");
System.out.println("Monitor Task Thread total Running Job taskWeight =" + sumRunningTasks);
System.out.println("Monitor Task Thread #" + taskId + ", remaining taskWeight = " + (taskWeight - taskWeightCounter));
if (sumRunningTasks > taskLoadLimit){
System.out.print("++++++++++++++++++++++++++++++++++++++++++++++>");
System.out.println("Task Load limit " + taskLoadLimit + "is exceeded by " + (sumRunningTasks - taskLoadLimit ));
}
}
}
}
}
class DispatcherTask4 extends Thread {
public int taskWeight = 600;
public int taskWeightCounter = 1;
private int taskId;
JobTask4[] runningTasks;

public DispatcherTask4(int taskId, JobTask4[] runnerTasks) {
this.taskId = taskId;
this.runningTasks = runnerTasks;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10+(int)(100*Math.random()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
{
for (int i = 0; i < runningTasks.length; i++) {
if (runningTasks[i] != null) {
if ((runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter) == 0) {
System.out.println("Dispatcher Task Thread dispatches new JobTaskkkkkkkkkkkkkkkkkkkkkkkkkkkk Thread #" + i);
runningTasks[i] = new JobTask4(i);
runningTasks[i].setPriority(2);
runningTasks[i].start();
break;
}
}
else {
runningTasks[i] = new JobTask4(i);
runningTasks[i].setPriority(2);
runningTasks[i].start();
}
}
System.out.println("Dispatcher Task Thread #" + taskId + ", remaining taskWeight = " + (taskWeight - taskWeightCounter));
}
}
}
}

3-A SIMPLE PROCESS SIMULATION

II. Upto here, when a JobTask is created by the JobQueue-Main routine at the beginning and when it finishes its weight it stops. This example provides a dispatcher which checks the runners queue which is passed to it via a parameter. After the check if the runners item is null it creates a JobTask3 thread object which has a fixed weight of 400. From now on, the JobQueue-Main routine does not create JobTask objects. It only creates the MonitorTask first and then creates the DispatcherTask. These tasks create JobTasks and monitor them as lonh as their own TaskWeights allow them. In fact these values are 400 for JobTask and MonitorTask and 600 for DispatcherTask in our example:


package stochasticprocess;

public class JobQueue3 {

private final static int NUMRUNNERS = 5;

public JobQueue3() {
}
public static void main(String[] args) {
JobTask3[] runners = new JobTask3[NUMRUNNERS];

// for (int i = 0; i < NUMRUNNERS; i++) {
// runners[i] = new JobTask3(i);
// runners[i].setPriority(2);
// }
//
// for (int i = 0; i < NUMRUNNERS; i++)
// runners[i].start();

MonitorTask3 monitorTask3 = new MonitorTask3(999, runners);
monitorTask3.setPriority(1);
monitorTask3.start();

DispatcherTask3 dispatcherTask3 = new DispatcherTask3(111, runners);
dispatcherTask3.setPriority(1);
dispatcherTask3.start();

}
}

class JobTask3 extends Thread {
public int taskWeight = 400;
public int taskWeightCounter = 1;
private int taskId;

public JobTask3(int taskId) {
this.taskId = taskId;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
System.out.println("Job Task Thread #" + taskId + ", taskWeightCounter = " + taskWeightCounter);
}
}
}
class MonitorTask3 extends Thread {
private int taskWeight = 400;
public int taskWeightCounter = 1;
private int taskId;
JobTask3[] runningTasks;
int sumRunningTasks;

public MonitorTask3(int taskId, JobTask3[] runnerTasks) {
this.taskId = taskId;
this.runningTasks = runnerTasks;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;
try {
sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
{
sumRunningTasks = 0;
for(int i=0; i < runningTasks.length; i++){
if (runningTasks[i] != null)
sumRunningTasks += runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter;
}
System.out.print("==========================================>");
System.out.println("Monitor Task Thread # Running Job Tasks=" + sumRunningTasks);
System.out.println("Monitor Task Thread #" + taskId + ", taskWeightCounter = " + taskWeightCounter);
}
}
}
}
class DispatcherTask3 extends Thread {
public int taskWeight = 600;
public int taskWeightCounter = 1;
private int taskId;
JobTask3[] runningTasks;

public DispatcherTask3(int taskId, JobTask3[] runnerTasks) {
this.taskId = taskId;
this.runningTasks = runnerTasks;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
{
for (int i = 0; i < runningTasks.length; i++) {
if (runningTasks[i] != null) {
if ((runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter) == 0) {
System.out.println("Dispatcher Task Thread dispatches new JobTaskkkkkkkkkkkkkkkkkkkkkkkkkkkk");
runningTasks[i] = new JobTask3(i);
runningTasks[i].setPriority(2);
runningTasks[i].start();
}
}
else {
runningTasks[i] = new JobTask3(i);
runningTasks[i].setPriority(2);
runningTasks[i].start();
}
}
System.out.println("Dispatcher Task Thread #" + taskId + ", taskWeightCounter = " + taskWeightCounter);
}
}
}
}

2-A SIMPLE PROCESS SIMULATION

II. I added a similar task with monitoring capabilities. MonitorTask has the same mechanisms as the previous JobTask but also it calculates for all the tasks in the runners queue the total of their remaining tasks as in:

sumRunningTasks += runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter;
The code is below:
package stochasticprocess;

public class JobQueue2 {

private final static int NUMRUNNERS = 5;

public JobQueue2() {
}
public static void main(String[] args) {
JobTask2[] runners = new JobTask2[NUMRUNNERS];

for (int i = 0; i < NUMRUNNERS; i++) {
runners[i] = new JobTask2(i);
runners[i].setPriority(2);
}

for (int i = 0; i < NUMRUNNERS; i++)
runners[i].start();

MonitorTask monitorTask = new MonitorTask(999, runners);
monitorTask.setPriority(1);
monitorTask.start();
}
}

class JobTask2 extends Thread {
public int taskWeight = 400;
public int taskWeightCounter = 1;
private int taskId;

public JobTask2(int taskId) {
this.taskId = taskId;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
System.out.println("Job Task Thread #" + taskId + ", taskWeightCounter = " + taskWeightCounter);
}
}
}
class MonitorTask extends Thread {
private int taskWeight = 400;
public int taskWeightCounter = 1;
private int taskId;
JobTask2[] runningTasks;
int sumRunningTasks;

public MonitorTask(int taskId, JobTask2[] runnerTasks) {
this.taskId = taskId;
this.runningTasks = runnerTasks;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;
try {
sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
{
sumRunningTasks = 0;
for(int i=0; i < runningTasks.length; i++)
sumRunningTasks += runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter;
System.out.print("==========================================>");
System.out.println("Monitor Task Thread # Running Job Tasks=" + sumRunningTasks);
System.out.println("Monitor Task Thread #" + taskId + ", taskWeightCounter = " + taskWeightCounter);
}
}
}
}

1-A SIMPLE PROCESS SIMULATION

This is an example for process simulation with simple and complete source codes for each development phase.
The first phase is taken from
http://www.java2s.com/ . My final example produces JobTasks with random weights at random moments of time and checks whether the total workload limit of a system of 5 workers is exceeded. The system can be made dynamic but queue length is constant in my examples.

I. There is a JobTask queue named runners which holds 5 Tasks. JobTask class is a thread which holds the task difficulty (or amount or duration) initially in the taskWeight variable and processes this value through the taskWeightCounter variable. Every time the task waits up it increases the taskWeightCounter and then waits for a constantt duration via sleep(10). A status message is printed when taskWeightCounter is a multiple of 50. The tasks are terminated when the taskWeightCounter reaches the value in the taskWeight. JobQueue – main routine instantiates the JobTasks in the runners queue and starts them.


package stochasticprocess;

public class JobQueue {

private final static int NUMRUNNERS = 5;

public JobQueue() {
}
public static void main(String[] args) {
JobTask[] runners = new JobTask[NUMRUNNERS];

for (int i = 0; i < NUMRUNNERS; i++) {
runners[i] = new JobTask(i);
runners[i].setPriority(2);
}
for (int i = 0; i < NUMRUNNERS; i++)
runners[i].start();
}
}

class JobTask extends Thread {
private int taskWeight = 400;
private int taskWeightCounter = 1;
private int taskId;

public JobTask(int taskId) {
this.taskId = taskId;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
System.out.println("Job Task Thread #" + taskId + ", taskWeightCounter = " + taskWeightCounter);
}
}
}