• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 299
  • Last Modified:

Making a class thread-safe

Hi All,

Can anyone tell me how they would make a simple class like the one below thread-safe?

  public class threadSafe {
        private ThreadSafe makeThreadSafe;
   
        public void setMakeThreadSafe(ThreadSafe threadVar) {
            makeThreadSafe = threadVar;
        }
   
        public Bar getMakeThreadSafe() {
            return makeThreadSafe;
        }
    }

I'm trying to learn a bit more a thread safety, obviously The class could be made a singleton and I could synchronize the set method.  Is there anything else I could do to make a simple class thread-safe.  Thanks.

0
zozig
Asked:
zozig
  • 2
1 Solution
 
hoomanvCommented:
the one you provided does not need thread safty

from the book java performance and tuning

Variables shared between multiple threads (e.g., instance variables of objects) have atomic assignment guaranteed by the Java language specification for all data types except longs and doubles. Actually, the storing of a value into a variable takes two primitive operations, a store and a write. However, the language specification also states that once a store operation occurs on a particular variable, no other store operation is allowed on that variable until the write operation has occurred. The (original[5]) specification allows longs and doubles to be stored in two separate sets of store+write operations, hence their exception to atomicity. A similar atomic specification applies for reading variables

This means that access and update of individual variables does not need to be synchronized simply to avoid corruption (as long as they are not longs or doubles). If a method consists solely of a single variable access or assignment, there is no need to make it synchronized for thread-safety, and every reason not to do so for performance.

0
 
hoomanvCommented:
> is also an atomic assignment
this assignment I think is also atomic
0
 
CEHJCommented:
Any methods should be marked synchronize that you want to be thread-safe
0
 
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now