MY own Executors class

The point of this would be something like Executors.newFixedThreadPool().
Comment/suggest/criticize on it please? I just wanted to take a whack at it :p
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class ExecutionService {
     public static void main(String[] args) throws Exception {
          ExecutionService executor = new ExecutionService();
          Runnable test1 = new Runnable() {
               @Override
               public void run() {
                    System.out.println("Test one complete!");
          Runnable test2 = new Runnable() {
               @Override
               public void run() {
                    System.out.println("Test two complete!");
          executor.executeAndWait(test1);
          executor.executeImmediately(test2);
     public ExecutionService() {
          runnableTasks = new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE);
          final int NUM_PROCESSORS = Runtime.getRuntime().availableProcessors();
          for(int i = 0; i < NUM_PROCESSORS; i++) {
               createNewExecutor();
     public Executor createNewExecutor() {
          return new Executor(new Runnable() {
               @Override
               public void run() {
                    try {
                         for(;;) {
                              getNewTask().run();     
                    } catch(InterruptedException e) {
                         e.printStackTrace();
                    } finally {
                         createNewExecutor();
     public boolean executeImmediately(Runnable task) {
          return runnableTasks.offer(task);
     public void executeAndWait(Runnable task) throws InterruptedException {
          runnableTasks.put(task);
     public Runnable getNewTask() throws InterruptedException {
          synchronized(this) {
               return runnableTasks.take();
     private LinkedBlockingQueue<Runnable> runnableTasks;
public class Executor {
     public Executor(Runnable task) {
          Thread t = new Thread(task);
          t.setDaemon(true);
          t.start();
}Edited by: Jadz_Core on Aug 6, 2009 4:37 PM

Hopefully it is to satisfactory now :)
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ExecutionService {
     public static void main(String[] args) throws Exception {
          ExecutionService executor = new ExecutionService();
          Runnable test1 = new Runnable() {
               @Override
               public void run() {
                    System.out.println("Test one complete!");
          Runnable test2 = new Runnable() {
               @Override
               public void run() {
                    System.out.println("Test two complete!");
          executor.waitToExecute(test1);
          executor.executeImmediately(test2);
     public ExecutionService() {
          runnableTasks = new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE);
          initializeExecutors();
     public ExecutionService(BlockingQueue<Runnable> blockingQueue) {
          runnableTasks = blockingQueue;
          initializeExecutors();
     private final void initializeExecutors() {
          final int NUM_PROCESSORS = Runtime.getRuntime().availableProcessors();
          for(int i = 0; i < NUM_PROCESSORS; i++) {
               createNewExecutor();
               ++numThreadsRunning;
     private final Runnable getPermTask() {
          return new Runnable() {
               @Override
               public void run() {
                    Exception ex = null;
                    try {
                         while(continueRunning) {
                              getNewTask().run();     
                    } catch(InterruptedException e) {
                         (ex = e).printStackTrace();
                    } catch(Exception e) {
                         (ex = e).printStackTrace();
                    } finally {
                         if(ex != null) {
                              createNewExecutor();
     private Executor createNewExecutor() {
          return new Executor(getPermTask());
     private Runnable getNewTask() throws InterruptedException {
          return runnableTasks.take();
     public boolean executeImmediately(Runnable task) throws Exception {
          if(!continueRunning) {
               throw new Exception("ExecutorService instance is shut down");
          return runnableTasks.offer(task);
     public void waitToExecute(Runnable task) throws InterruptedException, Exception {
          if(!continueRunning) {
               throw new Exception("ExecutorService instance is shut down");
          runnableTasks.put(task);
     public void shutDown() {
          continueRunning = false;
          Runnable emptyTask = new Runnable() {
               @Override
               public void run() {
                    return;
          for(int i = 0; i < numThreadsRunning; i++) try {
               waitToExecute(emptyTask);
          } catch(InterruptedException e) {
               System.out.println("Could not shut down!");
               e.printStackTrace();
          } catch(Exception e) {
               e.printStackTrace();
     private int numThreadsRunning = 0;
     private volatile boolean continueRunning = true;
     private BlockingQueue<Runnable> runnableTasks;
class Executor {
     public Executor(Runnable task) {
          Thread t = new Thread(task);
          t.setDaemon(true);
          t.start();
}

Similar Messages

  • Creating own Exception class

    In my past paper it says...
    Show how to create your own Exception class that derives from class Exception. The class should provide a default constructor which allows a "My Error message" message to be set, and a second constructor which has as an argument the error message. 4-MARKS
    Does this look right..?
    public class MyExcep extends Exception
         public MyExcep()
              super("My Error Message");
         public MyExcep(String message)
              super(message);
    }

    Yes. Do I get 4 marks now? or is it Four Marks?

  • Can applet load own security class, class loader

    i tried this own security class extends SecurityManager class but exception thrown as applet cannot initate new security manager class.
    i have done throw policy file entry to allow applet to write file in client machine.
    i feel this extra burden novice user...
    what is alternative way....
    plz..

    An applet should never be allowed to install its own security manager. That is why it is burdensome.

  • N00b query: Why would anyone ever want to define their own Exception class?

    I've been reading thru my Java textbook for the past couple hours.
    Exceptions are a wonderful thing. I already found several instances where I could've implemented try/cacth in my earlier programs.
    Anyway, getting back to the point. My question is, can someone give me a realistic situation/example where a custom Expcetion class is REQUIRED? (the key word here is "required"!)
    I can see why someone would want to have his own Exception class..... e.getMessage() as custom error messages are SO DAMN COOL!!!!!! :P
    hehe
    But seriously, if you are making intermidiate/advanced Java programs, would you ever REQUIRE to make your own Exception class? Afterall, even a custom made Exception class always "extends" from a pre-defined Java class, right?
    Let me make this a bit more clear... public class CustomException extends IOException{  }Now, if I am making a try/catch statement, I can simply say
    try{
    throw new CustomException;
    catch (IOException e) { }
    Now as you can see, the CustomException was caught by the catch claus, because IOException is the superclass of CustomException. So, in other words, the whole CustomException thingy didnt do anything useful.
    I know I know, I am so naive. Enlighten me >.<

    Sure. Say you want to have a system where you want to include a custom error code which maps to some internationalized error messages. You would create an Exception subclass with a field to hold that value separate from the normal "default" message. Then you could throw that exception in all your code. Other code can catch it as a plain Exception if they want and use the "default" message, which is okay if they don't really care about the error code.
    I don't think you are ever "required" to make your own exceptions. I have done so, but I don't often. It depends. See, there are plenty of Exception subclasses in the standard packages, and most of them cover many of the things you need. So more often if I'm throwing an exception, I'll be using the already existing ones, like IllegalArgumentException or IOException (whatever is relevant to the code).
    Yes, you can do what you did below with CustomException. However the reason you might do that is cuz you really want to do this:
    try {
       // call some code that may throw IOException from some standard IO package
       // or may throw CustomException from some of my methods...
    } catch (CustomException ce) {
       // handle cusotm exception
    } catch (IOException ioe) {
       // handle IO exception
    }Cuz you may want to differentiate between your exceptions vs. IOExceptions that might be thrown from some java.io class.
    Usually when you use an exception class it's a named class that relates to some condition. It may hold additional information besides the standard message, but I think most of the time it's just the class name which describes the problem. And if there isn't one that describes the problem that you're code might encounter, then create a subclass.

  • How to change local object to own dev class

    in the table maintenance generator my object is stored under local object how to change loacal object to our own development class and how to change the function group in table maintenance generator

    Hi Narendra,
    In order to change the function group, you need to delete the table maintenance generator first.
    Then you create a new table maintenance generator.
    To change the package of your object :
    1. for Function Group
       - tcode SE80
       - right click on the Function Group
       - choose : More Function - Object Directory Entry
    2. for Table / Function Module
       - tcode se11 / se37 / se38
       - in the upper menu : choose : Goto -- Object Directory Entry
    Hope this helps.
    best regards

  • How to change program from own develop class to $tmp

    hi,
    i m creating one program and stored under the development class ZFM.
    how can i change my own development class to $tmp(local object)i don;t want to use development class ZFM changed to $tmp

    1. SE38
    2. Give Program Name
    3. Use menupath: Goto-> Object Directory Entry
    4. Click on Display/Change in popup window
    5. Change the package to $tmp
    Make sure the object is not locked under any request.
    Kind Regards
    Eswar

  • Our own immutable class

    Hi,
    i have one requirement like ,need to develope my own immutable class like String class.if any one have sample code please post .
    Thanks,
    Anil.

    Make your class final. If you class has instance variables, make them private and final. Each instance variable's type itself should be immutable. If you do have mutable instance variables, then ensure when you write the class that you do not provide methods that mutate their values.
    - Saish

  • Using a SwingWorker in an Executor class?

    Here's some code that works and does what I want but I don't know if its a good idea....
    I have a program that may run one of a couple dozen long operations. I want to bring up a progress dialog to show the user how these operations are coming along.
    I was using a swing worker every time I ran a long task but its a pain to make changes in so many different places. So I set up the approach below.
    import java.util.concurrent.Executor;
    import javax.swing.JOptionPane;
    import com.sun.java.help.impl.SwingWorker;
    * This class takes a long task as a Runnable and
    * runs it while showing a progress dialog
    public class MyExecutor implements Executor
         public void execute(Runnable r)
              final MySmallProgressWindow dialog;
              dialog = new MySmallProgressWindow();
              final Runnable fr = r;
              dialog.show("Testing Executor ") ;
              final SwingWorker worker = new SwingWorker()
                   public Object construct()
                        try
                            fr.run();
                       catch(Exception g)
                             System.err.println(g);
                             JOptionPane.showMessageDialog(null, "Error: " + g.toString(), "Error", JOptionPane.ERROR_MESSAGE);
                       finally
                            dialog.hide();
                            System.out.println("Clean up here in finally");
                       return null;
                   public void finished()
                           dialog.hide();
             worker.start();
    I call it this way
    MyExecutor execute = new MyExecutor();                   
    Runnable runnableCopy = new Runnable() {
    public void run() {
         someLongTask();
    execute.execute(runnableCopy);Comments?
    Message was edited by:
    legoqueen

    import javax.swing.*;
    public class MyApplet extends JApplet {
         public void init() {
              //init stuff here
         public void start() {
              //start stuff here
         public static void main(String[] args) {
              JFrame f = new JFrame();
              JApplet a = new MyApplet();
              f.getContentPane().add(a);
              f.setSize(600, 400);
              f.setVisible(true);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              a.init();
              a.start();
    }Excuse me, but is there a way to do this on Applet only instead of JApplet... I was told we need to use Applet only...

  • Making Own Exception Class

    Hi all,
    I m trying to make a new exception class which will be called when when any sort of exception occurs.After throwing that class how can i call other exception in that class eg. if in a class if sqlexception occurs & i m throwing myclass so how can i catch sqlexception in myclass.

    if in a class if sqlexception occurs & i m throwing myclass so how can i catch sqlexception in myclass.
    you can throw your class object only when you catch the original exception. so pass the oroginal exception object in the constructor of your exception class.
    hope you get what i mean.
    - Azodious

  • Need help on creating my own exception class

    The program should check if the user entered a string larger than eight characters. If so, throw a user-defined exception. I'm getting the following errors:
    Any help is great.
    C:\Program Files\Xinox Software\JCreatorV3\MyProjects\StringTooLong\src\StringTooLong.java:25: <identifier> expected
    System.out.println("Enter a message less or equal of eight characters:\n:");
    ^
    C:\Program Files\Xinox Software\JCreatorV3\MyProjects\StringTooLong\src\StringTooLong.java:27: illegal start of type
    try
    ^
    C:\Program Files\Xinox Software\JCreatorV3\MyProjects\StringTooLong\src\StringTooLong.java:41: <identifier> expected
    ^
    3 errors
    import java.io.*;
    * The main logic class of the program.
    public class StringTooLong implements IOException
         BufferedReader br = new BufferedReader(new InputSTreamReader(System.in));
         String buffer = "";                    // Stores user input.
         // Tells the user what to do.
         System.out.println("Enter a message less or equal of eight characters:\n:");
         try
              buffer = br.readLine();
              if (buffer.length > 8)
                   throw new StringTooLongException;
              System.out.println("Your String: " + buffer);     
         catch (StringTooLongException e)
              System.out.println("\nThe string was too long!");
    class StringTooLongException extends Exception
         public StringTooLongException()
    }

    well you've mis-typed "InputStreamReader" (note capital t) and I don't think you want to be implementing IOException.
    Oh, and you're code isn't inside a method.
    Do this:public class WhateverItsCalled {
      public static void main(String[] args) throws IOException {
       // your code goes here
    // your other class here

  • Storing in an array from my own created class

    Hi,
    Here I am again with more questions. I am grovelling for help.
    I am working on a program in Netbeans 5.5.1 where I created a class called Student that gets and sets Last Name, First Name and Student ID. Now the program to run as a samle of this class will store the first Student I get and put it into slot [0] of my array and then I increment my NumStudents, as a count to moveon to the next array slot. The problem is that it only puts the Student info into slot[0], even on the 2nd or 3rd entry to store information. I'm not sure if the problem is in the gets and sets in my class or in my Store Info button listener.
    Here is a bit of the code. I have comments to help explain my problem.
    Thank you oh virtuosos of Java! This stuff brings me to tears!
    private void mouseclickedbtnStoreInfo(java.awt.event.MouseEvent evt)
    // Code to store info from the textbox entered by user:
    s.setFirstName(txtFirstName.getText());
    s.setLastName(txtLastName.getText());
    s.setStudentID(txtStudentID.getText());
    arrayAllStudents[NumStu] = s;
    NumStu++;
    txtFirstName.setText("");
    txtLastName.setText("");
    txtStudentID.setText("");
    //Testing array storage here also
    /*This only prints out only for the second student entered, loses the first, NumStu times, apparently only storing in slot 0. array is of Student class as is the variable s.*/
    for(int i=0;i<NumStu;i++){
    System.out.println(arrayAllStudents.getStudentID());
    System.out.println(arrayAllStudents[i].getFirstName());
    System.out.println(arrayAllStudents[i].getLastName());
    Hopefully this is not a challenging puzzle for all you experts out there. Pop me a line soon. I'll take my turn helping when I get this #*@& figured out.

    O.k. I'll try this again. We'll see if anything is clearer with this code. Before this I also have automatically generated code from Netbeans coding my gui. I also have another page of code generating my Student.class. The only methods I have in that are the sets and gets of StudentID, LastName, and FirstName.
        private void mouseclickedbtnStoreInfo(java.awt.event.MouseEvent evt) {                                         
    // Code to store info from the textbox entered by user:
            s.setFirstName(txtFirstName.getText());
            s.setLastName(txtLastName.getText());
            s.setStudentID(txtStudentID.getText());
            arrayAllStudents[NumStu] = s;
            NumStu++;
            txtFirstName.setText("");
            txtLastName.setText("");
            txtStudentID.setText("");
            //Testing array storage here also
            //This only prints out only for the second student entered and loses the first NumStu times
            for(int i=0;i<NumStu;i++){
                System.out.println(arrayAllStudents.getStudentID());
    System.out.println(arrayAllStudents[i].getFirstName());
    System.out.println(arrayAllStudents[i].getLastName());
    private void mouseClickedRetrieveInfo(java.awt.event.MouseEvent evt) {                                         
    // Code for user to retrieve the info from textboxes:
    //This is all printing out as only the last student entered but as many times as Num##.
    for(int i=0;i<NumStu;i++){
    System.out.println(arrayAllStudents[i].getStudentID());
    System.out.println(arrayAllStudents[i].getFirstName());
    System.out.println(arrayAllStudents[i].getLastName());
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new frmTestStudentClass().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton btnRetrieveInfo;
    private javax.swing.JButton btnStoreInfo;
    private javax.swing.JLabel lblFirstName;
    private javax.swing.JLabel lblLastName;
    private javax.swing.JLabel lblStudentID;
    private javax.swing.JTextField txtFirstName;
    private javax.swing.JTextField txtLastName;
    private javax.swing.JTextField txtStudentID;
    // End of variables declaration
    Student s;
    Student arrayAllStudents[] = new Student[MaxStu];
    }This does compile and run the gui. User can enter text into the textboxes and when I hit my StoreInfo button the textboxes clear and NumStu is incremented and first entrance is stored in arrayAllStudents[0].  This seemed to paste just as it is in Netbeans.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How I build my own libraries of classes/methods in java ?

    How I build my own libraries of classes/methods in java ? how then I refer a functionX() (i mean method) in LibraryX ? can you give a short/brief example of a library with a class with a method and a main method of normal class calling this method (of external's added library's) ?

    Just another cross poster.
    [http://www.java-forums.org/new-java/12389-how-i-build-my-own-libraries-classes-methods-java.html]
    db
    edit And [http://forums.java.net/jive/thread.jspa?messageID=305387]
    Edited by: Darryl.Burke

  • Putting own custom Writer class in the runtime enviornment of JSP

    Hello All:
    i have a doubt that i have made my own JSPWriter class and i want to use this class to be loaded in the runtime enviornment of the tomcat to get a custom output that is required by me .... for this i have written my own PageContext and through it i am instanciating this writer and successfully using it but is it the right procedure or i shall somehow need to follow some other procedure to get the task done. Another doubt that i have is if i load my suitable classes and in the runtime enviornment, will it effect the other applications that are running on the server ... and what ahould be the ways to overcome this .... is they follow the same procedure as i have then i think they are not supposed to face any problem ... kindly give me suggestions as i am in need of finding a solution as soon as possible ...
    One another thing that i need to ask is that if we want to read the contents that are being sent to the client brower through the JSP then how to get that .....
    I hope you will try to understand my urgency..
    thanks in advance
    Dodo

    Please read http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets8.html#82361 on filters and response wrappers. The advantage to this approach is that you can target your replacement writer to specific web resources and capture output.

  • Jni findclass cannot find my own classes with jre1.4

    I have a C++ program that uses CreateJavaVM() and FindClass() to access my own Java classes. Everything works as expected. Another C++ program uses
    GetCreatedJavaVMs() (returns 1)
    AttachCurrentThread()
    FindClass()
    to try to access other Java classes of my own. The GetCreatedJavaVMs() and AttachCurrentThread() seem to work fine but the FindClass() cannot find my own Java classes anymore.
    Shouldn't the VM and associated JNIEnv from GetCreatedJavaVMs be the same as that created using CreateJavVM() and thus be able to find the same classes? By the way, this worked fine with jre1.2 but stopped working when trying to move to jre1.4. Any ideas would be appreciated.

    hi...was wondering if you got that issue resolved.
    was it actually because of the newer JRE version?
    thanks.Considering that the post is about 2 years old, and that the person hasn't posted much since then here, I'd doubt he/she's going to respond to you. This isn't his/her email address, ya know.

  • Passing Wrapper Classes as arguments

    I have a main class with an Integer object within it as an instance variable. I create a new task that has the Integer object reference passed to it as an argument, the task then increases this objects value by 1. However the objects value never increases apart from within the constructor for the task class, it's as if it's treating the object as a local variable. Why?
    mport java.util.concurrent.*;
    public class Thousand {
         Integer sum = 0;
         public Thousand() {
              ExecutorService executor = Executors.newCachedThreadPool();
              for(int i = 0; i < 1; i++) {
                   executor.execute(new ThousandThread(sum));
              executor.shutdown();
              while(!executor.isTerminated()) {
              System.out.println(sum);
         public static void main(String[] args) {
              new Thousand();
         class ThousandThread implements Runnable {
              public  ThousandThread(Integer sum) {
                        sum = 5;
                        System.out.println(sum);
              public void run() {
                   System.out.println("in Thread : ");
    }

    AlyoshaKaz wrote:
    here's the exact queston
    (Synchronizing threads) Write a program that launches one thousand threads. Each thread adds 1 to a variable sum that initially is zero. You need to pass sum by reference to each thread.There is no pass by reference in Java
    In order to pass it by reference, define an Integer wrapper object to hold sum. This is not passing by reference. It is passing a reference by value.
    If the instructor means that you are to define a variable of type java.lang.Integer, this will not help, as Integer is immutable.
    If, on the other hand, you are meant to define your own Integer class (and it's not a good thing to use a class name that already exists in the core API), then you can do so, and make it mutable. In this case, passing a reference to this Integer class will allow your method to change the contents of an object and have the caller see that change. This ability to change an object's state and have it seen by the caller is why people mistakenly think that Java passes objects by reference. It absolutely does not.
    Bottom line: Your instructor is sloppy with terminology at best, and has serious misunderstanding about Java and about CS at worst. At the very least, I'd suggest getting clarification on whether he means for you to use java.lang.Integer, which might make the assignment impossible as worded, or if you are supposed to create your own Integer wrapper class.
    Edited by: jverd on Oct 27, 2009 3:38 PM

Maybe you are looking for

  • Internet access to the SolMan

    Hi, I want to know if it is possible to reach the SolMan via Internet access? We want to give the project members access to the project documentation in the Roadmap. Until now I could not find any practical links. But I have heard that´s possible via

  • How do I transfer a cd music library to my iphone 5 via itunes?

    I have copied across music to my Apple Mac from my old CD collection and want to transfer it to the iphone 5. The CD's show up in itunes but don't transfer onto the iphone. Any ideas gratefully received.

  • ESS framework in web dynpro for ABAP?

    Recently, I need to start an ESS project using web dynpro for ABAP. Unlike web dynpro for java, we have ESS framework in every track, like pcui/xx DCs and ess/per DCs in the track. And as there are existed projects in the DCs like ESS/JP/ADDRESS, we

  • Add file types to weblog media upload

    Is there a way to add more file types to the acceptable file types that can be uploaded to the weblog server?

  • Export BEx report to another system

    hello all,             we have BEx reports which we would like to send to other system. I tried some options and like to get more info. on the options.. openhub: not feasible as we r using hierarchies and complex queries rscrm_bapi / apd : does not s