• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

Multithreading issues

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,

I am new to Java multi-threading world. I have read "Head First Java" and other resources but still not clear about a few things like how to design a solution of a problem. For example: I went for an interview and they asked me this question:
Problem: Write code for a bus ticket reservation system.
1. Number of tickets available: 20
2. Each person will be able to reserve 5 tickets or none at a time.
3. Multiple threads will try to reserve the tickets
4. Print the final booking information

My code which is a mess. Can anyone help me out in making it better? Output is a mess. Threads doesn't synchronize. Same person is booked twice. Please help me design it in a better way.

Thanks.






 
Marshal
Posts: 65814
250
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I am afraid I would reject that code as soon as I saw a parameter called dot which hasn't anything to do with dots, or underscores in field_names.
I think you need a book about threading; most people don't use new Thread(...), but create a Thread Pool.
Please identofy which objects in your code aren't thread‑safe, for the first stage of the process.
Please explain what line 4 in the booking task class means.
 
Avi Sarma
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Welcome to the Ranch

I am afraid I would reject that code as soon as I saw a parameter called dot which hasn't anything to do with dots, or underscores in field_names.
I think you need a book about threading; most people don't use new Thread(...), but create a Thread Pool.
Please identofy which objects in your code aren't thread‑safe, for the first stage of the process.
Please explain what line 4 in the booking task class means.



Thanks!

Thanks for the quick reply as well.

Changed dot to something meaningful. Let me know what you think. New to java I will be more careful

>> The objects which should be safe are:
1. numOfTickets

My idea:
1. As I mentioned, thread should check the variable first. If number >=5, it should book tickets otherwise not.

Problem: Not sure, how to make the looping thread safe. I mean, if person 0 is booked by Thread-0, person-0 should not be booked by Thread-1...etc. Possible?

>> Line 4: It is the total number of tickets. So, my intention was if a thread changes it, it should be available to all the other threads. Tried volatile. But it didn't work. No idea why.

 
Campbell Ritchie
Marshal
Posts: 65814
250
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Avi Sarma wrote:. . . Thanks!. . .

That's a pleasure

. . . > The objects which should be safe are:
1. numOfTickets

That isn't an object

. . . If number >=5, it should book tickets otherwise not.

Where does the ≥ come from? It doesn't say anything about ≥ in your originall post.

. . . >> Line 4: It is the total number of tickets. So, my intention was if a thread changes it, it should be available to all the other threads. Tried volatile. But it didn't work. No idea why.

And why is that field marked static? Have you identified which objects are and which aren't thread‑safe?
 
Avi Sarma
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Where does the ≥ come from? It doesn't say anything about ≥ in your originall post.
>>Yes. that is just to explain the scenario. sorry if that confused you.
numOfTickets is not an object. yes. it is a variable which is not thread safe so made it static. this variable has the total number of tickets. initially it is 20.

2. And why is that field marked static?
>> the field is marked static so that there is only 1 copy for all threads to work on. this is initially 20. when a thread books a person, it reduces this static variable by 5.

3. Have you identified which objects are and which aren't thread‑safe?
>> object on which thread acts is BookingTask. So, i identify it as not thread safe. it has a method which is acted on by all threads. that method is not thread safe as well. so made it syncrhonized.

hope this helps and makes the situation a little bit clear
 
Campbell Ritchie
Marshal
Posts: 65814
250
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Avi Sarma wrote:. . . Yes. that is just to explain the scenario. sorry if that confused you.

No, it gives the impression that you are confused about the requirements. Partiluclarly when it says >= 5 in line 33 and 5 in line 39.

. . . >> the field is marked static so that there is only 1 copy for all threads to work on.. . .

So do you know why I think that is a serious mistake?

>> object on which thread acts is BookingTask. So, i identify it as not thread safe. it has a method which is acted on by all threads. that method is not thread safe as well. so made it syncrhonized. . . .

. . . and what does that method do? I can't understand it.
 
Avi Sarma
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably, I should try to explain with a scenario

Lets say there is a bus with 20 tickets available.

There is a list of 5 people.

There are two threads named Avi and Campbell.

Avi starts first and then Campbell.

My understanding:

Avi checks the number of tickets in the static variable. Oh, we got 20 tickets and 20 >= 5 for sure, so i should book the first person in the list.
I go into the loop, take the first person, puts in the register saying hey you got 5 tickets. congrats. booked by Avi. As method is synchronized, Campbell is still outside the method
waiting for Avi to get out. Once i booked the person-0, i come out of the door,  put the key in the nearby key holder.

Campbell gets the key and gets inside the method and checks the static variable. Aha, 15 more tickets, I should book a person. You go in, takes the name from the list, not sure
how you will get to Person-1, still a mystery for me , and then book him. You then reduce the number of tickets to 15-5 = 10, comes out of the method, keep the key in the key holder.

That is what I want to do. It seems my code is definitely not doing that. I am not able to think of a design to do that.

Any advice will be appreciated.

Why static variable is a bad idea? Not sure though. But i checked that When Avi goes out of method after putting Person-0, Campbell still sees Person-0 and so it puts the Person-0 in list again.

Probably, i am not designing the threads properly.
 
Saloon Keeper
Posts: 21133
134
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:
I think you need a book about threading; most people don't use new Thread(...), but create a Thread Pool.



It depends. In this case, the primary reason not to use a Thread Pool is that it's a basic Threading learning exercise and that would just complicate things.

A more general reason is that there's only a small fixed number of Threads. A Pool is best when you have a large number of threads popping in and out of use and you want to avoid the overhead of Thread creation and/or limit the total number of Threads allowed to run at one time (in which case, you'd often have a Thread Wait Queue as well).

On the other hand, if I recall correctly, there's a second way to create Threads, which is to have the Thread worker class extend class Thread directly, and that's what I'd probably use for a situation of the type portrayed. It's slightly simpler to code, although the net effect is the same.
 
Saloon Keeper
Posts: 5809
146
Android Mac OS X Firefox Browser VI Editor Tomcat Server Safari
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Avi Sarma wrote:numOfTickets is not an object. yes. it is a variable which is not thread safe so made it static.


Note that making a variable static does not make it thread-safe to use. To the contrary, it increases the chance of concurrency issues because now all threads have access to it.
 
Ranch Hand
Posts: 559
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tim Moores wrote:

Avi Sarma wrote:numOfTickets is not an object. yes. it is a variable which is not thread safe so made it static.


Note that making a variable static does not make it thread-safe to use. To the contrary, it increases the chance of concurrency issues because now all threads have access to it.



Hi Tim,

I chance upon this 'thread', could you explain how to make a variable static thread-safe then ?

Do we use singleton pattern in the case of different classes need to access a 'member variable' of a POJO class ?

To be more specific, cos I am also not sure what term to use.  When I mean member variable :

Example :



However, I also learnt that a singleton pattern uses synchronized which is bad.

Hope to have your views.

Thanks.
 
Campbell Ritchie
Marshal
Posts: 65814
250
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

tangara goh wrote:. . . how to make a variable static thread-safe then ? . . .

I think I shall join the Winston Gutkowski School of Computing and tell you there should be no such thing as a static variable in the first place.

singleton pattern . . . ..

Many people think it is called the Singleton Anti‑Pattern. Another thing you should probably avoid.
 
tangara goh
Ranch Hand
Posts: 559
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:

tangara goh wrote:. . . how to make a variable static thread-safe then ? . . .

I think I shall join the Winston Gutkowski School of Computing and tell you there should be no such thing as a static variable in the first place.

singleton pattern . . . ..

Many people think it is called the Singleton Anti‑Pattern. Another thing you should probably avoid.



I Google and I found java static variable.
B9F3D9EB-7114-4D62-B494-B01B6EB8B659.png
[Thumbnail for B9F3D9EB-7114-4D62-B494-B01B6EB8B659.png]
 
Campbell Ritchie
Marshal
Posts: 65814
250
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The fact that you can find an example on the Net doesn't necesarily mean it is a good thing.
 
tangara goh
Ranch Hand
Posts: 559
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:The fact that you can find an example on the Net doesn't necesarily mean it is a good thing.



Yes.  That's the reason I am seeking for an answer and solution.

Basically, I am faced with a situation where I need the attributes or Class members to be static and non-static at the same time.

So, example, if I want it static, I will call the static member and if the data get changed again due to the use case, I want another class to be able to call the non-static Class member.

How do I accomplish that ?

I am using Java servlet and jsp so I researched and found out people are using dependency injection.

But, uisng Java servlet I don't think it is possible to use dependency injection to achieve the above static and non-staic accessing....
 
Campbell Ritchie
Marshal
Posts: 65814
250
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure I understand the last question. You doubtless already know that you use public methods to access private fields.
 
Tim Holloway
Saloon Keeper
Posts: 21133
134
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

tangara goh wrote:

Campbell Ritchie wrote:The fact that you can find an example on the Net doesn't necesarily mean it is a good thing.



Yes.  That's the reason I am seeking for an answer and solution.

Basically, I am faced with a situation where I need the attributes or Class members to be static and non-static at the same time.

So, example, if I want it static, I will call the static member and if the data get changed again due to the use case, I want another class to be able to call the non-static Class member.

How do I accomplish that ?

I am using Java servlet and jsp so I researched and found out people are using dependency injection.

But, uisng Java servlet I don't think it is possible to use dependency injection to achieve the above static and non-staic accessing....



If you don't get your concepts straight, you're going to have a hard time.

Classes don't call classes. Methods invoke methods. Methods may access properties (members). If we're feeling generous, we'll let you use the term "call" for "invoke", but that's about it. Classes don't do anything. They're just containers for the methods and properties. Likewise, you cannot "call" a class, only methods within the class. This is true whether things are static or member scope.

Dependency injection is part of the concept of Inversion of Control (IoC), but I don't think that's relevant here. More to the point is that to make properties thread-safe, static and non-static are equally at risk. To be thread-safe, access to the property has to be synchronized.
 
Marshal
Posts: 14053
234
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One important point to accessing properties concurrently. If a property is immutable then it is inherently thread-safe and does not need synchronization. Only access to mutable shared state needs to be synchronized to be thread-safe.
 
Marshal
Posts: 7181
492
Mac OS X VI Editor BSD Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Avi Sarma, I'll comment on some other aspects.

Avi Sarma wrote:


Make all fields private. Always. Make classes final, unless you are planning to extend them. Make all fields final, unless there is a plan to mutate them - there isn't, so keep them final.

date_of_travel, variable name as such, isn't conventional in terms of its naming style. Better it would read as dateOfTravel, however, not sure the type String would suffice. You have been told already, that dot variable name is a dreadful name, so get rid of it. In fact, why dateOfTravel is in a Person's class in the first place? What it has to do with Person? When such questions arise, it is a good indication that something is off. Well, it didn't arise to you, but I hope you'll manage to see such misassignment of responsibility. I imagine for a person to have name and age is enough for now maybe. There could be some potential mapping between booked travels and persons who booked them, and the TravelBooking perhaps could have the date of trip. Doesn't it make sense, that TravelBooking would contain all the details related with the trip booking?
 
Liutauras Vilda
Marshal
Posts: 7181
492
Mac OS X VI Editor BSD Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Avi Sarma wrote:



1. Book class. I'd say it is a misleading name for the purpose it is created. Book also has different meaning, but of course from the context you could figure out what it actually means here, but I'd name it somehow differently. TravelBooking or along those lines...

2. ArrayList<Person> list. Quite often people have "Person[] list", which is confusing, because variable is called list, while the actual data structure is an array. In anyway, in both cases variable name "list" is a sign of poor name choice. What it represents? Ok, I see that it is a list of persons, and so what? What should I understand from that? Would it be clearer if I'd name it something similar to: unregisteredTravelers (not that clear too, but better), travelersToBookHotelsFor (purpose is clearer), again, something along those lines, the idea is name it clearly, what this collection of people represent. Having mentioned Traveler few times, maybe Person would better read as Traveler, having class name fit the domain better?

3. private static int i = 0; <-- what is that? Usually variable i is being used as a loop counter, which scope is strictly within the loop boundaries, and I think in most cases that should be kept that way. I think I know what you are trying to achieve here, but probably there are better ways to let know other workers which persons were registered already.
 
tangara goh
Ranch Hand
Posts: 559
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tim Holloway wrote:

tangara goh wrote:

Campbell Ritchie wrote:The fact that you can find an example on the Net doesn't necesarily mean it is a good thing.



Yes.  That's the reason I am seeking for an answer and solution.

Basically, I am faced with a situation where I need the attributes or Class members to be static and non-static at the same time.

So, example, if I want it static, I will call the static member and if the data get changed again due to the use case, I want another class to be able to call the non-static Class member.

How do I accomplish that ?

I am using Java servlet and jsp so I researched and found out people are using dependency injection.

But, uisng Java servlet I don't think it is possible to use dependency injection to achieve the above static and non-staic accessing....



If you don't get your concepts straight, you're going to have a hard time.

Classes don't call classes. Methods invoke methods. Methods may access properties (members). If we're feeling generous, we'll let you use the term "call" for "invoke", but that's about it. Classes don't do anything. They're just containers for the methods and properties. Likewise, you cannot "call" a class, only methods within the class. This is true whether things are static or member scope.

Dependency injection is part of the concept of Inversion of Control (IoC), but I don't think that's relevant here. More to the point is that to make properties thread-safe, static and non-static are equally at risk. To be thread-safe, access to the property has to be synchronized.



Well, I am here for the reason of getting my concepts right.

I know POJO is a stateless class.

However, when I created more classes or rather servlet to be precise I discovered i need to access to properties of my POJO sometimes using static and sometimes non static pro properties of the same property(properties).

And I would like to know how to make it happen ?
 
Junilu Lacar
Marshal
Posts: 14053
234
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

tangara goh wrote:Well, I am here for the reason of getting my concepts right.


That's a good start

I know POJO is a stateless class.


No, that is quite often not the case. See the definition of a Plain Old Java Object (POJO).

Any object that has instance fields is stateful. Any object whose state can be changed by any means, whether indirectly through a method call or directly via an assignment has mutable state. Any object whose state cannot be changed by any means after it is created has immutable state.

In order for it to be stateless, an object must have NO instance fields.

However, when I created more classes or rather servlet to be precise I discovered i need to access to properties of my POJO sometimes using static and sometimes non static pro properties of the same property(properties).


I don't understand what you mean by that, nor do I think others. Could you share a code example that illustrates what you're trying to explain?
 
Tim Holloway
Saloon Keeper
Posts: 21133
134
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And here's some more pedantry. You aren't "creating classes", you're instantiating objects.

A class is a definition. An object is a realization of that definition. That's why we have POJO - Plain Old Java Object, and not POJC - Plain Old Java Class.

And I'd say that not merely many POJOs are stateful, but that in fact the vast majority of them are. Because while an object housing immutable values does have its uses, most objects have at least some mutable properties.

And I am afraid I'm going to have to call out Junilu on that account. A class can have properties which are declared (or used) as final and be immutable. So an object doesn't have to lack properties to be stateless/immutable. A class of this nature might define a fixed set of properties such as a Look-and-Feel or a set of metric conversion factors.
 
Junilu Lacar
Marshal
Posts: 14053
234
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tim Holloway wrote:And I am afraid I'm going to have to call out Junilu on that account. A class can have properties which are declared (or used) as final and be immutable. So an object doesn't have to lack properties to be stateless/immutable. A class of this nature might define a fixed set of properties such as a Look-and-Feel or a set of metric conversion factors.


It could very well be that I'm wrong. I wouldn't be the first time, nor the last. I started out writing this:

- stateful + mutable (e.g. modifiable List)
- stateful + immutable (e.g. String)
- stateless, which I guess are immutable as well since there's nothing to mutate (e.g. a static class like java.util.Math with a bunch of library functions)

I may be mistaken in characterizing a class like String as stateful+immutable.

Or maybe we're saying the same thing only in different ways or very nuanced ways. ¯\_(ツ)_/¯

But thanks for calling me out on that. It made me think and that's always a good thing, even if it is a little early.
 
Tim Holloway
Saloon Keeper
Posts: 21133
134
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a sample of what I mean. I work with a CAD program which has the annoying feature that no matter how many different types of projects you have open, the same system of measurement applies to all of them. The metrics are global to the program, not per-project. But I do CNC and 3D print work mostly in metric, woodworking in either feet-inches or inches, depending on size, and architecture in feet-inches.

So I proposed a change to the system.

Since the GUI works from a common basis, to change metrics as you go from one project window to another, you need to have an easy way to switch the appropriate scaling and metric rendering options as you do so. The actual internal metrics of all projects are in micro-meters, but that's not what you'd normally specify when creating, measuring or putting dimension lines on components.

So I have a class named something like DrawingMetrics and I have several instances of this class. It holds the scaling factors, which are immutable values. That is, in Java terms, final, One is millimeters, so y, x, and z scale by 1000. One is inches-only, so the immutable scaling property is 25400 (give or take a factor of 10). One is inches/feet, so it's just like inches, except that another property in the class is a boolean value that tells the dimension renderer to output 1'11" instead of 23".

You can do something similar with stuff like volumetric conversions, and - to a lesser extent - with temperature conversions (some additional math is required). Or currency conversions, although those are volatile, so you'd either periodically discard instances and replace them or make them mutable.
 
tangara goh
Ranch Hand
Posts: 559
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

tangara goh wrote:Well, I am here for the reason of getting my concepts right.


That's a good start

I know POJO is a stateless class.


No, that is quite often not the case. See the definition of a Plain Old Java Object (POJO).

Any object that has instance fields is stateful. Any object whose state can be changed by any means, whether indirectly through a method call or directly via an assignment has mutable state. Any object whose state cannot be changed by any means after it is created has immutable state.

In order for it to be stateless, an object must have NO instance fields.

However, when I created more classes or rather servlet to be precise I discovered i need to access to properties of my POJO sometimes using static and sometimes non static pro properties of the same property(properties).


I don't understand what you mean by that, nor do I think others. Could you share a code example that illustrates what you're trying to explain?



Hi Junilu,

I managed to find the stackoverflow example which explains why used Singleton for enabling another class to access the class variable instead of static. So it will leave the ‘Base class’ to have non static.

Is that how things are done?

A31280DF-76C3-4C09-BD26-F00A9E423769.png
[Thumbnail for A31280DF-76C3-4C09-BD26-F00A9E423769.png]
 
Junilu Lacar
Marshal
Posts: 14053
234
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's an older method. I avoid emulating that pattern in my code. If you must, use an enum to implement singleton or a static helper.

See this article: https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples -- but make sure you read through the entire article and understand the implications for each option. The options I recommended are discussed towards the end of that article.
 
We're all out of roofs. But we still have tiny ads:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!