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

Similar Messages

  • 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)

  • Immutable and mutable object

    Here I want to post some solutions to immutable and mutable objects. First I'll brifely discribe the case when only one type (immutable or mutable) is need accross the application. Then, I'll describe case when both types is using. And finally, the case when only some object can modify this object, while for others it is immutable one. That will be illusrated on the objects discribing current date as number milliseconds from Zero Epoch Era (January 1, 1970).
    Let's start from an exampe for Immutable Object.
    public final class ImmutableDate {
        private final long date;
        public ImmutableDate(long date){
             this.date= date;
        public long getDate(){
            return date;
    }The class is final, so it is imposible to extend it (if it is possible to extend it, it will be possible to add some mutable data-members to the class. Data-member is final to avoid changing (if it is Object it is just warning to programmer not to change it, compiler just can check that reference wasn't changed, but state of this data-member can be changed). There is no method that returns reference to the data-member outside the ImmutableDate. (if data-member was immutable object,it would be possible to return refference to it, if data-member was mutable object and it was possible to revieve reference to it, than it was possible to change the state of data-member through setter function).
    Now, lets consider that we need only MutableDate. The implementation is obvious:
    public  class MutableDate {
        private long date;
        public MutableDate (long date){
             this.date= date;
        public long getDate(){
            return date;
        public void setDate(long date){
          this.date=date;
    }This is regular class.
    The question is how what should I do in the case I need both[b ]Mutable and Immutable Object. It is possible to use the above way of implementation. But there are following problems wih this:
    * Code is not re-usable. For example, getDate() is implemented twice.
    * Implementation is closed to the interface.
    * There is no abstraction such a Date. Usable, when we doen't care whether object is mutable or immutable.
    It will be also nice to have a mechanism to recieve immutable copy from any object. It can be implemnted as getImmutableDate() function. This function is usable, when we have Date object (or MutableDate) at hand and want to store it in HashMap. So immutable copy is needed. It also usable as deffencive copy of MutableDate, if want one to transfer Date to simebody we don't want to change the state.
    Second and third points leads us to declare interfaces:
    public interface Date {
      public long getDate();
      public ImmutableDate getImmutableDate(); 
    public interface ImmutableDate extends Date  {
    public interface MutableDate extends Date {
      public void setDate(long date);
    public final class ImmutableDateImpl implements Date, ImmutableDate {
    public class MutableDateImpl  implements Date, MutableDate {
    }Lets talk more on the first point. In this short example it will look like it is not bug disadvantage. But think, that there are ten data members and setting other value isnot trivvial (for example, other private data members should be recalculated) and you'll realise that this is a problem. What solution OO proposed in such a cases? Right, inheritance. But there is one pitfalls here. Immutable object has to be final (see explanation above). So the only way to do this is to define some new class and inherit from him. It will be look like the following:
    abstract class AbstractDate implements Date  {
       protected long date;
       public AbstractDate(long date){
         this.date=date;
       public long getDate(){
         return date;
    public final class ImmutableDateImpl extends AbstractDate implements Date, ImmutableDate {
      public ImmutableDateImpl(long date){
        super(date);
      public final ImmutableDate getImmutableDate(){return this;}
    public class MutableDateImpl extends AbstractDate implements Date, MutableDate {
      public MutableDateImpl(long date){
        super(date);
      public void setDate(long date){
        this.date=date;
      public final ImmutableDate getImmutableDate(){
        return return new ImmutableDateImpl(date);
    }Note that AbstractDate is declare package-private. It is doing to avoid casting this type in the application. Note also that it is possible to cast immutable object to mutable (interface MutableDate doen't extends ImmutableDate, but Date). Note also that data memer is
    protected long date;That is not private, but protected and not final. It is a cost of getting re-usability. IMHO, It is not big price. Being protected is not a problem, IMHO. Final is more for programmer, rahter than to compiler (see explanation above). Only in the case of primitive data type compiler will inforce this. programmer can know, that in he shouldn't changed this value in AbstractDate, and ImmutableDate, and he can do it only in MutableDate.
    I want to write some words about getImmutableDate() function. This function is usable, when we have Date object (or MutableDate) at hand and want to store it in HashMap. So immutable copy is needed. It also usable as deffencive copy of MutableDate, if want one to transfer Date to somebody we don't want to change the state.
    Let consider the following scenarion. We are writting a game, say chess. There are two players, that plays, desk where they play, and environmemnt (arbiter) that enforces rules. One of the players is computer. From OO point of view the implementation has to the following. There is Desk that only Environment can modify it. ComputerPlayer has to be able only to view ("read") the Desk, but not to move figute ("write"). ComputerPlayer has to talk with Environment what he want to do, and Environmnet after confirmation should do it. Here desk is immutable object to everyone, but Environment.
    If we go back to our Date, the implementation of this scenario could be
    interface AlmostImmutableDate extends Date {
      public void setDate(long date);
    public class Class1 {
      public static ImmutableDate getImmutableDate(long date){return new AlmostImmutableDateImpl(date);}
      private static class AlmostImmutableDateImpl implements Date, ImmutableDate/*, AlmostImmutableDate*/ {
        private long date;
        public AlmostImmutableDate(long date){
          this.date=date;
        public long getDate(){
          return date;
        public void setDate(long date){
          this.date=date;
        public final ImmutableDate getImmutableDate(){
          return this;
    } Which such implementation only Class1 can modify AlmostImmutableDateImpl. Others even don't know about existance of this type (it is private static class).
    It is possible to extends somehow to the case, when not one object, but (a little) group of object can modify Date. See the code above with uncommented part. One way to this is to difine new interface, say AlmostImmutableDate, with package-private scope. AlmostImmutableDateImpl will implements this interface. So, all object that has the same package as AlmostImmutableDate will can to cast the object to this type and modify it.
    Note, that AlmostImmutableDate has to extend Date interface (or ImmutableDate), but not MutableDate! If it will extand MutableDate, than it wiil be possible to cast to MutableDate in any package.
    If there is no MutableDate object in the application, so AlmostImmutableDate is unique. If there is MutableDate object in the application and we want to construct such almost immutable object, so copy&paste is needed to declare AlmostImmutableDate interface.
    Summary.
    It is difficult to define really pair of immutable object and mutable object in Java. Implementation consuming time and not very clear. There are many points to remember about (for example, data-member is not final, or order of inheritance, immutable object has to be final, and so on).
    I want to ask. If these solutions are complete? That is, it is not possible to modify immutable object or almost immutable objects not in the package of AlmostImmutableInterface. Not using reflexion, of course.
    Is these solutions are not to complicated?
    What do you think about delcaration of the third class AbstractDate? Has it to implement date? Perhaps, it is possible to define Date as abstract class (as AbstractDate was)? What do you think about definning
    protected long date;in AbstractDate?
    What do you think about function getImmutableDate() defined in Date interface? Perhaps, it should be declared in other place (even other new interface) or shouldn't be delcare at all?

    It seems to me that you are over thinking the problem:
    Why not just:
    public interface Date {
        long getDate();
    public interface MutableDate extends Date {
        void setDate(long);
    public class ImmutableDate implements Date
        final long date;
        public ImmutableDate(long date){
             this.date= date;
        public ImmutableDate(Date date){
             this.date= date.getDate();
        public long getDate(){
            return date;
    public class ModifiableDate implements MutableDate
        final long date;
        public ModifiableDate(long date){
             this.date= date;
        public ModifiableDate(Date date){
             this.date = date.getDate();
        public long getDate(){
            return date;
        public void setDate(long date){
            this.date = date;
    }

  • 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.

  • 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;

  • 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!

  • Trade-offs of different Immutability designs

    Hi,
    I'm wondering what the trade-offs are for the following immutability designs:
    1) Object composition: a mutable class wraps an immutable class without any sort of inheritance. Example: String vs StringBuilder.
    2) Single interface with optional operations. Example: List throws UnsupportedOperationException when someone tries modifying an immutable list.
    3) Object inheritance: a mutable class extends an immutable class. Example: MutableString extends String by adding mutation methods to it. I could not find an example of this in the JDK.
    4) Are there other possible designs you're familiar with?
    Thank you,
    Gili

    Why would you need to do this? Why couldn't the mutable interface inherit from the immutable one?I was originally talking about classes where if the super is immutable then you quite literally cannot make it muttable (like String).
    But to answer the direction of the inheritance tree problem (mutable->immutable or vice versa), if Mutable extended Immutable it's then fundamentally not an Immutable breaking the "is a" rule, you have this problem with both directions of inheritance. More reason to steer clear of it I think.
    Deciding what modifiability to return/accept is an even more tricky business with both inherited route and with distinct classes, for example imagine the .iterator() method you would have to duplicate the methods to: mutableIterator() and immutableIterator(), this would plague your API designs and make it a royal pain to use.
    I meant unmodifiable class, not immutable.The discussion works for immutable and unmodifiables, though I think that converting between (im)mutables becomes even hairier (should be avoided) as users are lead to believe the internal class will never change, whereas unmodifiables allow the internal class data to change just not via API calls.
    I should explain that my "interest" here is the best way to introduce "turning modifiability on and off" (which is only a slight deviation to the original post). In my case, I've decided it's a must have feature.
    Why would the caller ever need to know whether a Collection is mutable or not?Where we've experienced this issue we've been designing an API that's not just a collection, more like heavyweight resources, where:
    -in certain cases we don't trust the user to give them access to the modifiable
    -where they can only receive/read from the resource and they should not alter it
    -to let them register interest in the resource before it's construction is finalised - ensuring they don't interrupt the finalisation process.
    -the API is about the same size as the collections API, which I think is bordering on the (to) largish size (if it's a small API I'd consider distinct classes).
    The decision was made to give them the ability to discover whether the resource was unmodifiable for two reasons:
    -code could be written (annoying that it's not "have to be" I agree) which would then be guaranteed not to fail unexpectedly later on (assuming compliance).
    -not having it meant that users are subtly encouraged to to write large chunks of code within an �ber try/catch to handle possible failures, which has it's obvious disadvantages.
    I also believe there should be some method of discovering whether the resource/collection is unmodifiable. Say you want fail fast behaviour for example, you have to call some modifiable method and deal with the resulting exception if it failed. And (slightly worse) try and undo it if it did work - which in some cases is impossible.
    In most cases (e.g. collections being used) this isn't required, as generally the collection's modifiability will stay the same for an apps lifetime and good testing (or the first time the error is discovered :) will out any mistakes which can be fixed once and for good.
    I think that Josh got it right when designing the collections framework, I can't see a better way of doing it given the size of the resulting API and ignoring the "not being able to discern modifiability" problem. Adding anything other than a tagging interface or simple checking method would have resulted in a seriously bloated API.
    I think the reason they didn't do anything about trying to discern modifiability was that, as collections don't change their modifiability (accepting composition), they probably decided, as you said, there's no benefit to adding the ability to check.
    I followed the link btw, it's interesting to get other peoples take on these issues, I constantly worry if I'm going down the right route. I am trying to get a few of our projects made open source so I can get other peoples feedback/input for that very reason.
    Wowsers, I also didn't realise I had this much to say about it, sorry.

  • Factory pattern returning shared mutable objects

    We have a non-EJB load-balanced environment of JSP/Business Objects
    with JMS synchronized caches. Here's an overview.
    Business objects stored in a custom in-process cache (one instance per JVM) and the caches are synchronized using JMS. The business objects are maintained through utility classes (not exactly factories) with the
    following pseudo -code logic
    public static Object getObject(Object id) {
    try {
    Get from cache...
    } catch(.. e) {
    load from database
    put it in cache.
    Currently we return the cached object "as-is" to the calling code. The objects being mutable this poses a risk of some JSP/bean inadvertently changing the cached copy. Although this is the fastest approach we have quickly realized that it is no longer safe.
    I am unable to find good patterns that address this common problem. Most patterns I have seen are very EJB centric and some of them boil down to the pseudo-code I have shown above. Which is not
    the solution but the problem itself!
    Is there anyway I can return an immutable instance of our objects in a generic way?. I know the alternatives..
    1) Clone. Create extra objects. It so happens the cached objects are actually shown in an end-user GUI tree on a web-page accessed by 200 concurrent users. cloning would create a copy per get call.
    2) Create an immutable and mutable version of the class and return only
    the immutable version. How do I ever get the mutable version with this approach
    This seems like a fairly common problem and I was wondering if anybody has solved this a little more elegantly then what I have presented above.

    2) Create an immutable and mutable version of the class and return onlythe immutable version. How do I ever get the mutable version with this approach
    The setter use no modifier or with protected modifier, the getter use public modifier.
    private String name;
    public String getName() {
       return name;
    String setName(String name) {
       this.name = name;
    }When the class is used outside the package, it is immutable, but it become mutable if accessed from class within the same package.
    This means, the cache manager class also need to be placed in the same package in order to gain mutable access.
    rgds,
    Alex

  • [disc]Design pattern - immutable objects.

    I`m working more often with immutable object because it doesn`t cost as much work to keep object consistent. But sometimes an object has to be build or a reference to his child objects has to be set.
    eg
    class A{
        private ArrayList bList = new ArrayList();  
        public A(){}
        public void addB(B b){
            bList.add(b);
    class B{
        private A a;
        public B(A a){
             this.a = a;
    }It`s now more complicated to make a immutable version of A.
    My question is how this problem could be solved. One solution is to add an immutable flag that could be set to true if the last B is added. But this couldn`t be checked compile time.
    Maybe there is a design pattern for this problem.
    I would like to discuss about this problem, so every thought is welcome.

    I have an Immutable Collection wrapper class that I use when I want to have a Collection be read-only.
    If you look at the JavaDoc for AbstractCollection you'll see that the add and remove methods throw UnsuportedOperationException.
    So all you have to do is implement the iterator() and size() methods. i.e.
    public class ImmutableCollection extends AbstractCollection {     
         private Collection collection;
          * only constructor
         public ImmutableCollection(Collection collection) {
              this.collection = collection;
          * returns the size of the collection
         public int size() {
              return collection.size();
          * returns a non-modifiable iterator over the elements of the collection
         public Iterator iterator() {
              return new Iterator() {
                   Iterator iterator = collection.iterator();
                   public boolean hasNext() {
                        return iterator.hasNext();
                   public Object next() {
                        return iterator.next();
                   public void remove() {
                        throw new UnsupportedOperationException();
    }

  • String immutability

    Hi
    I am confused when they say that string is immutable and we need to use StringBuffer instead....
    But why the piece of code below is compiling if string be immutable ?
    public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
    String  mystring ="Hello how are you ";
    mystring ="Are you fine ";
    System.out.println(mystring);
    }

    nogoodatcoding wrote:
    Second, Strings are immutable because once created, you cannot modify their content. That's fixed.Except...
    import java.lang.reflect.*;
    public class ImmutableStringDemo {
        public static void main(String[] args) throws Exception {
            String string = "foo";
            assert "foo".equals(string);
            new StringChanger().change(string);
            assert "bar".equals(string);
    class StringChanger {
        public void change(String s) throws IllegalAccessException {
            Field[] fields = s.getClass().getDeclaredFields();
            for (Field f : fields) {
                f.setAccessible(true);
                if (f.getType() == char[].class) {
                    f.set(s, "bar".toCharArray());
    }Don't try this at home, all standard caveats apply.
    ~

  • How can I pass an object to a function by value?

    Hi
    I have a function with an argument. this argument is an object. I don't want to alter this object. But java passes this object by reference and some fields in this object are altered after function return.
    How can I pass this object by value and keep my original data unbroken?
    thanks for any help

    a.toraby wrote:
    I have a function with an argument. this argument is an object. I don't want to alter this object. But java passes this object by reference and some fields in this object are altered after function return.
    How can I pass this object by value and keep my original data unbroken?How you approach it is likely to depend on how much control you have over the code in question. If it's legacy code and has been badly designed, there's probably very little you can do to protect existing code short of a complete refactoring.
    What you could do as an interim measure is:
    1. Create an immutable wrapper to your existing mutable class.
    2. Create new methods that replicate the existing ones, but take the immutable class instead.
    3. Deprecate the old methods.
    This won't break client code, but they will now get warnings when they compile and you can add documentation to point them to the new class/methods.
    If you are in control of the code (especially if you're still in the design stages), you've got several options:
    1. As Dr.Clap says, make your class immutable (probably best).
    2. If this isn't possible, create mutable and immutable variants of your class. This is often best achieved by hanging them both from an interface.
    Winston

  • Cannot concat string

    when i have the following program, the system print out at last is just "good" instead of "goodhello", do I make any mistake?
    thx~
    import java.io.*;
    import java.lang.Object;
    import java.lang.String;
    public class Test{
    public static void main(String[] args) throws IOException {
    String c = "good";
    String d ="hello";
    c.concat(d);
    System.out.println(c);

    In Java, Strings are immutable. All String manipulation functions return new Strings and leave the originals unchanged.
    c.concat(d);This creates and ignores a new, separate, String object. c is left unchanged.
    You could have done as the previous poster recommended and used c = c.concat(d);or c += d; c then points (yes, Java does have pointers!) to the newly-created String object.
    You could also use the mutable class StringBuffer:
    c = new StringBuffer(c).append(d).toString();For a simple concatenation, this offers no readability or efficiency benefits over +, but it's useful in other circumstances.

  • Is Struts framework WLS cluster-safe?

    In a clustered WLS environment, there are programming requirements
              having to do with the use of the session object ("Session Programming
              Requirements" in http://edocs.bea.com/wls/docs61/cluster/servlet.html).
              The Jakarta Struts framework uses the session object extensively.
              Does anyone know whether Struts complies with the above requirements
              and is therefore WLS cluster-safe? Has anyone deployed a Struts-based
              application to a WLS cluster?
              

    Let's look at it without synchronization:
    Thread A calls execute() method (no class variables that are not constants)
    Thread B calls execute() method (no class variables that are not constants)
    Let's look at it with synchronization:
    Thread A calls execute() method (synchronization check succeeds)
    Thread B calls execute() method (synchronization check hangs until thread A is done and releases the lock)
    Let's say that the execute() method does something with decent latency (like accessing a network resource or a database). Now, you eventually end up with a 'queue' of threads waiting for the lock to be released. This is a scaling constraint. It introduces a bottleneck into your application.
    Now, this is sometimes unavoidable. For example, database connections are a scarce resource. The solution to this is a connection pool, which helps, but does not eliminate the bottleneck. Wherever possible, you want to avoid scaling bottlenecks.
    You have the ability to do so in your case. Try to avoid anything in your Action class itself (a class variable) that is anything other than a String or a primitive and ensure that any of those variables are constants (static and final). Now, these variables are 'thread-safe' because they are constant and immutable.
    For your execute() method, only use variables that are in the method signature itself or created/declared within the execute() method. This will ensure your Action class is in fact thread-safe. The minute you declare a mutable class variable (or a class like List that allows you to manipulate its contents), you introduce the possibility of a race condition and thread-unsafety (if that's a real term).
    - Saish

  • Tiger (1.5.0) Pearls...

    I've reading some Tiger documentation and noticed that there is a new method reverseBytes in java.lang.Integer and Long classes. (There are also some other methods, like rotateLeft and rotateRight and a funny method called reverse, that reverses the order of the bits).
    Several times in the forum we are asked about "how to change the order of bytes in a int/long because I am communicating with a C++ program in a Intel machine". Now there is a function for it.
    Talk about some new feature of Tiger (not the major ones, like generics, varargs, foreach, annotations, printf, but the little-noticed ones, like the reverseBytes method.)

    StringBuilder is a classic case of the dialog between languages...
    1) Java created the String and its sibling, StringBuffer
    2) Anders Hejslberg designs J++ from the Java spec
    3) Anders Hejslberg designs C# and copies the String class design (String is immutable, its sibling class StringBuffer is mutable), but the sibling of the String class is StringBuilder instead of StringBuffer - a better chosen name ("buffer" is an implementation detail; "builder" describes the target use).
    4) The maintainers of the Java language study C# and borrow some useful ideas (like metadata). They choose to use StringBuilder instead of StringBuffer for constructing Strings now.

  • Noob problems plz help

    hello, making a program called overunder and i just cant seem to get it
    * Modify the class "OverUnder".
    * Provide appropriate names and data types for each of the instance variables. Maintain two dice, credit balance, total of both dice, current message and the prediction.
    * Define appropriate "final" fields that allow you to use meaningful words instead of integers for the current prediction. Final fields should be in ALL CAPS. Refer to Section 5.13.2 for a brief description about final fields.
    * public OverUnder ( ) - a constructor that initializes all of the instance variables to appropriate values including instantiating two GVdice.
    * public void predictOver ( ) - Update the prediction to reflect OVER if there is at least once credit and update the message to confirm the prediction and prompt the player to roll. Otherwise, update the message to explain the player must add more credits and do not update the prediction.
    * public void predictUnder ( ) - Update the prediction to reflect UNDER if there is at least once credit and update the message to confirm the prediction and prompt the player to roll. Otherwise, update the message to explain the player must add more credits and do not update the prediction.
    * public void predictSeven ( ) - Update the prediction to reflect SEVEN if there is at least once credit and update the message to confirm the prediction and prompt the player to roll. Otherwise, update the message to explain the player must add more credits and do not update the prediction.
    * private void checkOver ( ) - Check if the current dice total is over seven. If it is, increase credits by one and update the message to congratulate the player. If not, decrease credits by one and update the messaage to inform the player. Note: this method is designed to be 'private' since external objects should not be allowed to invoke it. However, it could also be designed as 'public' like the rest of the methods.
    * private void checkUnder ( ) - Check if the current dice total is under seven. If it is, increase credits by one and update the message to congratulate the player. If not, decrease credits by one and update the messaage to inform the player.
    * private void checkSeven ( ) - Check if the current dice total is equal to seven. If it is, increase credits BY THREE and update the message to congratulate the player. If not, decrease credits by one and update the messaage to inform the player.
    * public void roll ( ) - If a prediction has been made, 1) roll both dice, 2) update the dice total, 3) invoke one of the appropriate methods to check for a correct prediciton: checkOver( ), checkUnder( ) or checkSeven( ) and 4) reset the prediction to NONE. If a prediction has not been made, remind the player to make a prediction by updating the message but do not roll the dice.
    * public void printMessage ( ) - print the internal message to the terminal window. Note: there are no print statements anywhere else in the class and this method will be ONLY ONE LINE of code!
    * public int getCredits ( ) - return the current credit balance.
    * public void addCredits (int amount) - add the provided amount to the credit balance. Set an error message if the value is less than or equal to zero and do not modify the credit balance.
    * public GVdice getDie (int num) - return the requested die. Legal values for "num" are 1 or 2. Note, this method is only used for the GUI version.
    * public String getMessage ( ) - return the internal message. Note, this method is used for the GUI version and is ONLY ONE LINE of code!
    any ways to go about doing this, how do i make a final variavle OVER when its always changing
    thx

    any ways to go about doing this, how do i make a final variavle OVER when its always changingYou don't. "final" means that it doesn't change.
    If you're assignment seems to be telling you to make something both final and mutable (and if you think I'm going to wade through what you posted, you're crazy), then ask your professor for clarification. If your professor can't clarify, or is really expecting you to make something both final (immutable) and mutable, then get a new professor as the current one is worthless.

Maybe you are looking for

  • Keyboard shortcut for the Document Folder in file open/save dialog

    Does anyone know if there exists a keyboard shortcut for Document Folder in the File Save/Open Dialog? <command><shift>O works in the Finder. I tried variations of that in the dialog and didn't find any. <command>D takes you to the desktop. I tried o

  • Unable to view the Fields  inside Segment

    Hi, We are doing IDOC---File scenario We have one IDOC "WPDWGR01" in R/3 and we imported that into IR. When we are doing the mapping, that time we are unable to see the fields that inside this  "E1WPW02" segment. We have BEZEICH and VERKNUEPFG fields

  • Time Capsule won't back-up my new hard drive

    I added a new hard drive to the drives I want Time Capsule to back-up. I get an error message that says "reformat required (case sensitive disk)" when I try to add the new drive. When I exclude this drive from back-up the error message goes away, but

  • Genius Problem With App Stor

    Hello, I received my iphone 5 last week. I noticed that Genius freez and makes me return to the springboard. If I sign out of my account in Settings > itunestore/appstore > Apple ID > Disconnect : Genius Works ! Can you help me to fix it ? thx a lot

  • How can I programati​cally add items to an Expression​Edit ComboBox?

    Items can be statically added using the ActiveX Properities/ComboBoxItems.  How can this be done programatically from C#?  I am using C# 2008 and TestStand 4.1. Solved! Go to Solution.