Solved

Constructor question

Posted on 1998-11-19
1
215 Views
Last Modified: 2010-03-30
I would like multiple thread within a process to access
a common data.
I put the common data in a class and declared it static
i.e public class A {
           static int data1;
           static string data2;

           public synchronized int makechanges()
           {
              //make changes to static data...
           }
   }
my question regards the constructor for this class.
Obviously I would like to initialize data1 & data2 at
the start of the program.
But I can't initialize data1 & data2 in the constructor since each instantiation of this class by a
thread will reset the existing static data.
I could just set a flag as another static field in the
class to deal with this problem.
But is this the best way to get multiple threads to share data ?

Thanks
0
Comment
Question by:kkandasa
1 Comment
 
LVL 5

Accepted Solution

by:
msmolyak earned 20 total points
ID: 1227895
What you need is a static initializer which is executed once when the class is loaded by the class loader.

public class A {
               static int data1;
               static string data2;
               static
               {
                 data1 = ...
                 data2 = ...
               }
.

This is of course not the only way for the threads to share data, but this is the simplest. other ways are passing a non-static object reference to each thread, making an object a singleton with a static method getXXX() which returns a reference to a single object instance (it is similar to making the object static but the user does not know it is static).

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
The viewer will learn how to implement Singleton Design Pattern in Java.

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

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

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now