Keeping a queue class immutable

Hi,
I recently got hooked on the concept of immutable classes. I'm not really sure why, but anyway...
I have a class that queues up tasks to a worker thread for execution, which is currently immutable. However, I never implemented a way to stop the worker thread if I wanted the queue to shutdown, so I'm trying to come up with a way to do so while retaining the immutability of the class.
Normally, I'd have a boolean value, and then set the boolean to false or true or whatever, and then the run() method in the worker thread would return. However, If I have to set a boolean, it would break the concept of immutability.
So while this question may seem somewhat ridiculous, I'm more curious than anything to see if there's a way to solve this problem.
Here's my queue class, with an incomplete shutdown() method, which I'd like to, in the future, "stop" the ThreadWorker thread:
public final class ThreadQueue {
     private final ExecutorService pool;
     private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(5);
     public ThreadQueue() {
          pool = Executors.newSingleThreadExecutor();
          (new Thread(new ThreadWorker())).start();
     public synchronized void addToQueue(Runnable task) {
          try {
               queue.put(task);
          } catch (InterruptedException ignored) {
     public void shutdown() {
     private final class ThreadWorker implements Runnable {
          public void run() {
               for (;;) {
                    try {
                         pool.execute(queue.take());
                    } catch (InterruptedException ignored) {
}If I'm just being pedantic with the whole immutability thing, so be it; I'm really curious.
Any advice will be greatly appreciated.
Thanks,
Dan

Well it looks as if I need to look up the definition of immutable again. I didn't think that adding things to a list would constitute changing the state of the object, but now that I think about it, that obviously does.
Anyway, my question is answered; the question was a bit ridiculous like I had thought, but oh well.
> >
It seems to me tho that while shutdownNow could potentially stop the pool (which it seems is just 1 thread), it won't stop the other threads... BTW, all the threads seem to do is to loop and tell the single executor to run the next job... Are they actually running the jobs? Otherwise, why do you need more than 1 of them?
As to this, shutting down the ExecutorService stops that thread, and it won't stop the thread running from ThreadWorker (which is why I changed my code as I'll show later). Anyway, the point of ThreadWorker is to execute each task in a "background" thread. Actually, since the ExecutorService runs in its own thread, it seems as if ThreadWorker is pretty worthless. If I added pool.execute(queue.take());it doesn't seem like it'll matter. Looks like I'll have to try that out and see what happens.
Anyway, here's the most recent update of my code, with the new shutdownQueue() method and a new loop in ThreadWorker:
public final class ThreadQueue {
     private final ExecutorService pool;
     private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(5);
     private volatile boolean stopThreadWorker;
     public ThreadQueue() {
          pool = Executors.newSingleThreadExecutor();
          stopThreadWorker = false;
          (new Thread(new ThreadWorker())).start();
     public synchronized void addToQueue(Runnable task) {
          try {
               queue.put(task);
          } catch (InterruptedException ignored) {
     public void shutdownQueue() {
          stopThreadWorker = true;
          pool.shutdownNow();
     private final class ThreadWorker implements Runnable {
          public void run() {
               while(stopThreadWorker) {
                    try {
                         pool.execute(queue.take());
                    } catch (InterruptedException ignored) {
}Thanks for all the help!

Similar Messages

  • Making a class immutable

    Ho w to make a class immutable??
    Thanx in advance

    Example
    import java.util.Date;
    * Planet is an immutable class, since there is no way to change
    * its state after construction.
    * @is.Immutable
    public final class Planet {
      public Planet (double aMass, String aName, Date aDateOfDiscovery) {
         fMass = aMass;
         fName = aName;
         //make a private copy of aDateOfDiscovery
         //this is the only way to keep the fDateOfDiscovery
         //field private, and shields this class from any changes
         //to the original aDateOfDiscovery object
         fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());
      //gets but no sets, and no methods which change state
      public double getMass() {
        return fMass;
      public String getName() {
        return fName;
      * Returns a defensive copy of the field.
      * The caller of this method can do anything they want with the
      * returned Date object, without affecting the internals of this
      * class in any way.
      public Date getDateOfDiscovery() {
        return new Date(fDateOfDiscovery.getTime());
      // PRIVATE //
      * Primitive data is always immutable.
      private final double fMass;
      * An immutable object field. (String objects never change state.)
      private final String fName;
      * A mutable object field. In this case, the state of this mutable field
      * is to be changed only by this class. (In other cases, it makes perfect
      * sense to allow the state of a field to be changed outside the native
      * class; this is the case when a field acts as a "pointer" to an object
      * created elsewhere.)
      private final Date fDateOfDiscovery;

  • Strategy to make a mutable class immutable

    Hi,
    i posted this topic in the wrong forum:
    http://forum.java.sun.com/thread.jspa?threadID=5129395&messageID=9463016#9463016
    Could you help me?
    (I mentioned it already to the moderator)

    class Immutable {
    final Mutable delegatee;
    public Immutable(Mutable m) {
    delegatee = m; // <---- You must create adefensive copy of m first.
    ImmutableChild getChild() {
    return new ImmutableChild(delegatee.getChild());
    Note that you must create a defensive copy of the
    Mutable object in your Immutable constructor.
    Otherwise the caller can modify the supposedly
    Immutable through the Mutable reference it passed to
    the constructor.Like Stefan, i don't see your point. In this example, the only caller who can change the original mutable object, is the wrapper class. But that's no problem because the wrapper is designed by the creator of the mutable object.
    If you look to my specific problem, and you create a class SourceUnit, who has a reference to the class ImmutableAST, which is an immutable wrapper of my AST node class, i don't see how the client, that calls the method instanceOfSourceUnit.getImmutableAST() can modify the original abstract syntax tree (under condition that the the wrapper class does not delegate to original AST methodes that can change the state of the tree and that the fields it returns are also immutable (wrapper) classes)

  • How can 1 make an object of user defined class immutable?

    Hi All,
    How can one make an object of user defined class immutable?
    Whats the implementation logic with strings as immutable?
    Regards,

    Hi All,
    How can one make an object of user defined class
    immutable?The simple answer is you can't. That is, you can't make the object itself immutable, but what you can do is make a wrapper so that the client never sees the object to begin with.
    A classic example of a mutable class:
    class MutableX {
        private String name = "None";
        public String getName() {
            return name;
        public void setName(String name) {
            this.name = name;
    }I don't think it's possible to make this immutable, but you can create a wrapper that is:
    class ImmutableX {
        private final MutableX wrappedInstance;
        public ImmutableX (String name) {
            wrappedInstance = new MutableX();
            wrappedInstance.setName(name);
        public String getName() {
            return wrappedInstance.getName();
        // Don't give them a way to set the name and never expose wrappedInstance.
    }Of course, if you're asking how you can make your own class immutable then the simple answer is to not make any public or protected methods that can mutate it and don't expose any mutable members.
    Whats the implementation logic with strings as
    immutable?
    Regards,I don't understand the question.

  • Keep getting VncViewer.class not found error when trying to use Windows 7

    Greetings,
    I have no issue accessing the OVM Manager 2.2 with OEL 5.4 x86_64 with the latest Java release from ULN. But when I use a Windows 7 client ( x86) with the Sun Java 6 Update 18 I get the following error when trying to access the Console of a VM Guest:
    Java Plug-in 1.6.0_18
    Using JRE version 1.6.0_18-b07 Java HotSpot(TM) Client VM
    User home directory = C:\Users\deverej
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    load: class VncViewer.class not found.
    java.lang.ClassNotFoundException: VncViewer.class
         at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.IOException: open HTTP connection failed:http://141.144.112.202:8888/OVS/faces/app/VncViewer/class.class
         at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
         at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
         at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         ... 7 more
    Exception: java.lang.ClassNotFoundException: VncViewer.class
    I am curious fi I should use only a specifc Java Engine with IE 7 or the latest Firefox browers.

    Same issue to with Windows XP SP3 x86 with Java Runtime Enviornment 1.5.0_15
    J2SE Enviornment 5.0 Update 15
    Java 6 Update 17

  • Flash Builder 4.6 - How can I keep unit test classes out of the finished swc?

         I have a library of code I'm building and I'm working on unit testing but I have a major issue. When my finished swc compiles no matter what I do it includes the unit test classes as part of the intellisense if you load the swc via flash. The classes aren't really in the swc since if you just try and import them they'll come up undefined. They only appear to go into the intellisense for the swc. Does anyone know how can I keep this from happening in the finished source? Currently my folder setup is like this in flash builder.
    src\main - source documents for the library to get compiled
    src\mock - mock class area for unit testing
    src\test - unit test classes
         In the project Properties panel > the first tab of my Flex Library Build path I have selected only the src\main folder for the classes to inlude in the library. No other folder paths are selected.
    The "Flex Library Build Path" doesn't change my results with any setting.
    Thanks,

    Mel Riffe,
    Here's a Help topic about compiler options in Flash Builder: http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb524b8220812e5611f28f-7fe7. html
    For information on using mxmlc, the application compiler, to compile SWF files from your ActionScript and MXML source files, you can see: http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7fcc.html
    Hope this helps,
    Mallika Yelandur
    Flash Builder Community Help & Learning
    Adobe Systems Incorporated

  • How to make a class immutable?

    I hav attend the interview where they ask this question.
    I know little bit is Make the class final and declare all variables as static final .
    Can any Help me.
    This question

    Thi is just my opinion;
    An immutable object is an object that once created, it's values can no longer be changed.
    Thus an immutable object could be an object that allows it's values to be changed only when created with the use of the constructor, and only has get methods to retrieve those values (no set methods).
    @Peetzore
    Defining them as final is something I never did, however it makes sense :) and will start doing so as well
    Regards,
    Sim085

  • Where should I keep my utility classes...

    Hi All,
    I have WAR application and few ejb JARs which are sharing common utility classes. I have created a separate folder for my WAR application. ejb jars also are in the serverclasses folder.
    Now the question what's the recommended destination for utility classes. Can I keep them in the WAR application.
    regards,
    Aravind.

    If you are totally unsure, you can create a folder somewhere, put the files in it and then add the folder to your $PATH.

  • Problems with exporting gradients in svg // illustrator keeps adding strange classes

    I'm currently working on some icons for our new agency website... When try to export  files with gradients, which assigned to nicely named graphic styles, illustrator keeps exporting a strange st-class for every new gradient i'm generating and refuses to assign my class, like:
    <style type="text/css">
              .testStyle{fill:url(#SVGID_1_);}  //my class with a useless gradient
              .st0{fill:url(#testrect_1_);} // class generated by illustrator
    </style>
    <linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"> // useless gradient with no height?!
              <stop  offset="0" style="stop-color:#FFFFFF"/>
              <stop  offset="1" style="stop-color:#000000"/>
    </linearGradient>
    <linearGradient id="testrect_1_" gradientUnits="userSpaceOnUse" x1="118" y1="200.5" x2="400" y2="200.5"> // correct gradient
              <stop  offset="0" style="stop-color:#FFFFFF"/>
              <stop  offset="1" style="stop-color:#000000"/>
    </linearGradient>
    <rect id="testrect" x="118" y="117" class="st0" width="282" height="167"/>
    </svg> // rectangle which should have .testStyle on it
    In a correct way, it should be:
    <style type="text/css">
              .testStyle{fill:url(#testrect_1_);} 
    </style>
    <linearGradient id="testrect_1_" gradientUnits="userSpaceOnUse" x1="118" y1="200.5" x2="400" y2="200.5"> // correct gradient
              <stop  offset="0" style="stop-color:#FFFFFF"/>
              <stop  offset="1" style="stop-color:#000000"/>
    </linearGradient>
    <rect id="testrect" x="118" y="117" class="testStyle" width="282" height="167"/>
    </svg>
    When i change the code by myself, it works properly. But it's actually no option to change every svg by hand...
    Do you have any ideas what's happening there and how to possibly avoid it?!
    Thanks in advance,
    Flo

    how to possibly avoid it?!
    Don't use Illustrator?! Sorry, but you're dealing with the dumbest program on the planet when doing SVG in AI. Which of course is ironic, considering Adobe kinda invented the format. If you want code-style control, you probably will have much better luck with any other program or even JavaScript-based online SVG generators. Possibly you can do some of that with Edge, also, but I don't use it in any way, so I can't vouch for how extensive and usable its SVG features are.
    Mylenium

  • I want to make this class immutable. How to optimize performance?

    Hi,
    I designed an immutable class for other people to use. And I'm wondering if there's any way to optimize it for performance.
    ie.
    class MyImmutableList
      final List myList;
      public MyImmutableList(List list)
        myList = list;
      public MyImmutableList append(Item item)
        List copy = myList.copy();
        copy.append(item);
        return new MyImmutableList(copy);
    }But I find that many times, other people use the class like this:
    someList = someList.append(item);So in a case like this, append() is unnecessarily making a copy of the list.
    Is there anyway to optimize this?
    Thanks
    -Cuppo
    Edited by: CuppoJava on 20-Jul-2008 5:44 AM
    Edited by: CuppoJava on 20-Jul-2008 5:44 AM

    DrClap wrote:
    Well, of course, what else should they do when the method returns an ImmutableList?
    What I would do with that append() method would be to remove it from the API entirely. The class is supposed to be immutable? Then it doesn't need an append() method. Unless, of course, the append() method isn't meant to change the state of the object, which seems a bit, let's say, unintuitive. Returning a copy of the list with the object appended then wouldn't change the state of the object, but it would return a new object. Which in fact is what the code does. But why? I'm like those other people, I would do that too. I don't understand the purpose of the method.The Defence calls java.math.BigDecimal
    >
    BigDecimal, would it be fair to say, you are an immutable class?
    It would.
    Would it also be true to say that you have an add() method?
    I do
    And would it be fair to say that adding could be construed as a mutating operation?
    I suppose so
    And what does this method do, given that you claim to be immutable?
    It returns a new object which is the result of the add() operation
    Thankyou

  • Where to keep the java class file which is being used from a form?

    Hi,
    Actually I am developing a form which has a bean area and the data will be displayed in the bean area in the form of grid. And I will register this form with apps and will run the from Oracle apps. I want to know that there is a java class file that is being refered by the form, where should this java class file be placed and is there any other places where any changes are required so that the form runs correctly from the Oracle apps and can find the java class file.
    I am very thankful to each and everyone who will be able answer this question of my.

    do you mean decompiling? there are tons of java decompilers available out there, what exactly are you trying to do here?

  • A map to keep track of classes and interfaces of all api's

    Sorry because of my english, i hope someone can help me by telling me if there is a sort of map or schema in which graphically be deployed all api's clases in a uml style; i wish that resource exists and be able to be downloaded for free; if someone replies my answer thankyou very much.

    smithdale87 wrote:
    i dont think you will find a UML of all classes and API's.
    The closest I can get you is http://java.sun.com/javase/6/docs/api/
    Experiment with these links at the top of the page - Overview, Package, and Tree
    Selecting Overview and Tree shows all of the class hierarchy.
    Selecting Package and Tree shows it for that package.
    This is close to what you want.

  • How to you keep "active" pseudo-class, well, active?

    By default, the a.link:active state is shown only for as long as the button on the mouse is pressed. When you let go, it reverts back to the regular a.link state.
    How do I make the active state STICK? In other words, in a navigation menu that is permanently on the screen, I want the active state to stick permanently (until another button is pushed).
    How is this accomplished?
    Thanks!

    Consider this code -
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <style type="text/css">
    .foo {
              color: red;
              font-weight: bold;
    </style>
    </head>
    <body>
    <p><a id="num1" href="#" onclick="this.className='foo';document.getElementById('num2').className='';">Foo</a></p>
    <p><a id="num2" href="#" onclick="this.className='foo';document.getElementById('num1').className='';">Foo</a></p>
    </body>
    </html>

  • Queue class Circular List Please HELP

    Hi guys i have coded an enQueue() is suppose to be a circular list but rather it work just like a list.
    i have posted the doubt as comment
      public void enQueue(T e)
             Node<T> newNode = new Node<T>(e,null);     //this constructor is rather complicated most sample of circular list i seen just use =new Node<T>()
                   if (isEmpty())                                        //can roughly tell me why the need for Node<T>(e,null)
                        newNode.next = newNode;              
                  else
                       newNode.next=tail.next;     //this portion only link the node to the next node but how do i modified it such that the      
                       tail.next=newNode;          //last node will be link to First node at the front     
             tail=newNode;
            size++;
        }Edited by: ryaner84 on Sep 29, 2008 11:50 PM
    Edited by: ryaner84 on Sep 30, 2008 4:33 AM

    Unless this is homework, don't create your own lists.
    If this is homework you should find examples of circular linked lists with google.

  • Immutable Vs Mutable Classes

    Hi.
    I want to know the following:
    1. What are immutable classes/objects?
    2. How to implement an immutable class?
    3. Is Math class immutable? I know it's final but is it immutable? what's the difference?
    4. Difference between Immutable/Mutable class - Implementation wise...
    Thanks

    Hi.
    I want to know the following:
    1. What are immutable classes/objects?An immutable object is one whose internal state (its fields or instance variables) cannot be changed once it has been created. An immutable class... I guess that would be a class whose objects are immutable.
    2. How to implement an immutable class?Make all instance variables private and do not provide any methods that change them.
    3. Is Math class immutable? I know it's final but is
    it immutable? what's the difference?The question doesn't apply, because you cannot create an object of class Math. The modifier "final" means that you cannot declare a subclass of the class; it has nothing to do with whether its objects are immutable.
    4. Difference between Immutable/Mutable class -
    Implementation wise...?
    >
    Thanks

Maybe you are looking for

  • Order Text in Sales Order

    Hi Gurus, I am trying to create a sales order thru BAPI.I am able to see an order_text item in the line item level of the BAPI. Where exactly does it show in the line item of the sales order. I tried to enter values but i am unable to see it in the l

  • Have to keep restarting phone

    The past few days my iPhone 4S has been giving me problems. It freezes causing me to do hard reset. It keeps shutting off my wifi and when I **** off phone and turn it back on wifi will be back on. I open texts and it gives me blank screen but works

  • How do I change the Sort order for Music Video's on the iPad

    Hi All, Apologies if this has been dealt with elsewhere - I can find posts about sort order for TV Shows and Movies but not Music Video's. When I sync my music video's the appear in Track order in the video app and I cannot find how to change the sor

  • EJB server\default directory not found

              this is the error that i am getting when i deploy my war and I           am not able to figure out what is server\default EJB directory.           can some one help in realizing what mighht be the problem           <Mar 22, 2001 3:15:39 PM

  • Not able to use RUN_PRODUCT in Oracle Apps11.0.3

    I am getting FRM-40733 error when trying to call a report from forms. I have registered the form and when calling the report Iam getting the FRM-40733 error. Please let me know what can be done . Thanks, Previn