The moose likes Threads and Synchronization and the fly likes Help with counter Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Help with counter " Watch "Help with counter " New topic
Author

Help with counter

Jonny Kidd
Greenhorn

Joined: Feb 02, 2006
Posts: 13
Hi all,
Been a long time since I've posted on here, good to see the forums are as lively and helpful as ever!
OK, I will try and explain my problem (no wisecracks...!) as easily as I can.

Class Y extends Thread.
Class X creates a number of new Class Y 'threads'.

I would like a counter somewhere that all the Class Y threads can update (ie any of them can increment the counter by one).
Is it just as simple as creating a Static variable in Class X or is it not quite this simple ?

Cheers all,
Jon
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24061
    
  13

Hi,

Welcome back!

You could put the counter in class X, but since it's code in class Y that will be using it, it makes more sense to put it in Y. But either place is OK, I suppose. It doesn't actually need to be static: if a single instance of X is creating all the Ys, then that X can pass itself to Y as a constructor argument, and all the Ys can use the counter in that one X. It's actually best to avoid static variables when you can -- gives you more flexibility.

OK, now, as to whether it's that simple or not... not really. You can't just let all the threads access that single variable, or updates could be missed due to the way data can be cached locally to each thread. You have to use synchronized access methods to ensure that each thread always sees the latest data, and that no writes get lost. So minimally, you need something like this:



And then all your code needs to use these methods rather than accessing "counter" directly.

I'm going to move this to our "Threads and Synchronization" forum for further discussion.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help with counter
 
Similar Threads
Threads again
Duplicate problem
how the program works?
is ++x threadsafe?
Up Casting