?
Solved

Thread Pool using java 5 and queue

Posted on 2007-07-27
6
Medium Priority
?
2,288 Views
Last Modified: 2010-08-05
How do we write Thread Pool using java 5.
I want to create Thread Pool from which i should be able to run and queue the task.

I mean that
 
 runThread(Runnable r)
 checkavailableThreadsInPool
 getActiveThreadCount - returns number of active Thread

Any suggestion , sample code?
0
Comment
Question by:BHUSHANGEETE
4 Comments
 
LVL 92

Accepted Solution

by:
objects earned 1000 total points
ID: 19583055
0
 

Author Comment

by:BHUSHANGEETE
ID: 19583066
In this we cant control number of threads running now.
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 1000 total points
ID: 19583877
Here's some code i wrote a couple of years ago for EE:


import java.util.PriorityQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.Executors;


/**
 *      Description of the Class
 *
 * @author             CEHJ
 * @created            20 February 2005
 */
public class Switch extends PriorityQueue<Packet> {
      /**
       *      Description of the Field
       */
      public final static long serialVersionUID = 0xDEFACE;

      /**
       * Decimal fraction of initial capacity used to calculate
       * the absolute value at boundary (see below)
       */
      private double boundaryLimitAsDecimal;
      /**
       * Absolute value at boundary, calculated by
       * boundaryLimitAsDecimal * initialCapacity
       * e.g. in a Switch with initialCapacity capability
       * of handling 50 packets initially, with a boundaryLimitAsDecimal
       * of 0.5, boundaryLimitAsAbsoluteValue would be 25, i.e. the boundary
       * would be applied at the 25th packet to arrive at the switch
       */
      private int boundaryLimitAsAbsoluteValue;
      /**
       * The priority that must be held by the packet
       * in order to be allowed to enter the switch once
       * the boundary condition is reached
       */
      private int minimumPriorityAtBoundary;
      /**
       * The initial number of packets that the switch
       * is designed to handle, although the switch can
       * grow to accommodate more
       */
      private int initialCapacity;


      /**
       *Constructor for the Switch object
       *
       * @param      initialCapacity                         Intial number of packets allowed into the switch.
       *      Used in calculating the boundary (see below)
       * @param      boundaryLimitAsDecimal      Decimal fraction of initial capacity used to calculate
       * the absolute value at boundary (see above)
       */
      public Switch(int initialCapacity, double boundaryLimitAsDecimal) {
            super(initialCapacity);
            this.initialCapacity = initialCapacity;
            this.boundaryLimitAsDecimal = boundaryLimitAsDecimal;
            boundaryLimitAsAbsoluteValue = (int) (initialCapacity * boundaryLimitAsDecimal);
            System.out.printf("Switch: initial capacity = %d, boundary = element %d\n", initialCapacity, boundaryLimitAsAbsoluteValue);
      }


      /**
       *      Sets the minimumPriorityAtBoundary attribute of the Switch object
       *
       * @param      minimumPriorityAtBoundary      The new minimumPriorityAtBoundary value
       */
      public void setMinimumPriorityAtBoundary(int minimumPriorityAtBoundary) {
            this.minimumPriorityAtBoundary = minimumPriorityAtBoundary;
      }


      /**
       *      Gets the minimumPriorityAtBoundary attribute of the Switch object
       *
       * @return            The minimumPriorityAtBoundary value
       */
      public int getMinimumPriorityAtBoundary() {
            return minimumPriorityAtBoundary;
      }


      /**
       *      If a boundary condition (see above) has been reached, then only
       *      packets of priority < minimumPriorityAtBoundary will be allowed
       *      into the switch. Yes, this is confusing, but the confusion is
       *      grounded in the fact that Sun orders the priorities in a PriorityQueue
       *      such that the lowest numeric values have the highest priority, so we approach
       *      things likewise.
       *
       * @param      packet      The packet arriving at the switch
       * @return                         As per Queue.offer
       */
      public boolean offer(Packet packet) {
            synchronized (this) {
                  System.out.println(this);
                  System.out.println("Head=" + peek());
                  System.out.printf("Offering packet %s to the switch...\n", packet.toString());
                  boolean boundaryCondition = (size() >= boundaryLimitAsAbsoluteValue);
                  if (boundaryCondition) {
                        System.out.println("At boundary condition");
                        if (packet.getPriority() <= minimumPriorityAtBoundary) {
                              System.out.printf("Accepted offer for packet id %d\n", packet.getId());
                              return super.offer(packet);
                        }
                        else {
                              System.out.printf("Refused offer for packet id %d\n", packet.getId());
                              return false;
                        }
                  }
                  return super.offer(packet);
            }
      }


      /**
       *      The main program for the Switch class
       *      Start a Switch with initial capacity of 50
       *      with a boundary condition occurring at half-way
       *      to capacity, i.e. at the 25th packet's arrival
       *
       * @param      args      The command line arguments
       */
      public static void main(String[] args) {
            Switch switch_ = new Switch(50, 0.5);
            switch_.setMinimumPriorityAtBoundary(2);
            new PacketGenerator(switch_, 50, 5).generate();
      }


}

/**
 *      Generate numberOfPackets packets and send them to Switch switch_
 *
 * @author             CEHJ
 * @created            20 February 2005
 */
class PacketGenerator {


      private ThreadFactory packetFactory;
      private Switch switch_;
      private int minPriority;
      private int numberOfPackets;



      /**
       *Constructor for the PacketGenerator object
       *
       * @param      switch_                              The target switch
       * @param      numberOfPackets      Number of packets to generate
       * @param      minPriority                  Upper number for priority, which is
       * in fact the lowest priority
       */
      public PacketGenerator(Switch switch_, int numberOfPackets, int minPriority) {
            this.switch_ = switch_;
            this.numberOfPackets = numberOfPackets;
            this.minPriority = minPriority;
            packetFactory = Executors.defaultThreadFactory();
      }


      /**
       *      Description of the Method
       */
      public void generate() {
            for (int i = 0; i < numberOfPackets; i++) {
                  packetFactory.newThread(new Packet(switch_, i, (int) (Math.random() * minPriority))).start();
            }
      }
}

/**
 *      Description of the Class
 *
 * @author             CEHJ
 * @created            20 February 2005
 */
class Packet implements Comparable, Runnable {


      private static int MAX_SLEEP_DURATION = 5000;
      private int priority;
      private int id;
      private Switch switch_;



      /**
       *Constructor for the Packet object
       *
       * @param      switch_       The switch targeted by this packet
       * @param      id                        Description of the Parameter
       * @param      priority      Description of the Parameter
       */
      public Packet(Switch switch_, int id, int priority) {
            this.switch_ = switch_;
            this.id = id;
            this.priority = priority;
      }


      /**
       *      Gets the priority attribute of the Packet object
       *
       * @return            The priority value
       */
      public int getPriority() {
            return priority;
      }


      /**
       *      Gets the id attribute of the Packet object
       *
       * @return            The id value
       */
      public int getId() {
            return id;
      }


      /**
       *      Description of the Method
       *
       * @param      o      Description of the Parameter
       * @return            Description of the Return Value
       */
      public int compareTo(Object o) {
            Packet otherPacket = (Packet) o;
            return priority - otherPacket.priority;
      }


      /**
       *      Sleeps for a random time before hitting the switch
       */
      public void run() {
            // Sleep for random time
            try {
                  Thread.sleep((int) (Math.random() * MAX_SLEEP_DURATION));
                  switch_.offer(this);
            }
            catch (Exception e) {
                  e.printStackTrace();
            }
      }


      /**
       *      Description of the Method
       *
       * @return            Description of the Return Value
       */
      public String toString() {
            return String.format("<[id=%d,priority=%d]", id, priority);
      }

}
0
 
LVL 1

Expert Comment

by:Computer101
ID: 20296338
Forced accept.

Computer101
EE Admin
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month15 days, 18 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question