Win a copy of Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams this week in the Reactive Progamming forum!
  • 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

Static class

 
Greenhorn
Posts: 10
Linux Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

When  a class doesnt need instance but only need global access , Shoud I create it like static  ? Always ?

Thanks
 
Marshal
Posts: 14039
234
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Standard consultant's answer: "It depends (on the context)."

You might want to give more a specific context otherwise, you might get conflicting answers based on the assumptions that the replies are based on.

And Welcome to the Ranch!
 
Saloon Keeper
Posts: 21128
131
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Experience: no matter how many static classes I create, sooner or later most of them seem to end up as non-static. Static is easy to locate, but very limiting to use. So one of the best uses of static is to provide a factory for non-static instance(s).
 
Marshal
Posts: 65782
250
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

What's a static class? We see that term often enough, but I think it is at best imprecise. Many people use it to refer to a class whose every member is static, but that sort of code often represents a utility class (also called helper class). That is code which has no purpose of its own, but exists to provide services to other code. If you look up Math, Arrays or Collections, you will find they serve to provide serices for other classes. They all have the same features:-
  • 1: All members static.
  • 2: Only private constructors, as explained in the Java® Language Specification (=JLS).
  • 3: No data of their own, maybe only constants.
  • If you stick with those features, you can remain with utility classes. Otherwise, you will end up with data different from object to object, in which case, as Tim H said, you will end up with an ordinary class.
    Avoid making things static in ordinary classes, though that is sometimes impossible to achieve completely. Also I think you should avoid calling classes static; it is usually class members that are static rather than the classes themselves.
     
    Tim Holloway
    Saloon Keeper
    Posts: 21128
    131
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Actually, it's my utility classes that so often end up non-static over time and use.

    My definition of "static class" is a class whose resources - methods and/or members - are entirely static and thus no construction is done. Anything else is simply an object class that might just happen to be loaded with static stuff.
     
    Campbell Ritchie
    Marshal
    Posts: 65782
    250
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Tim, should we impute some sort of distinction between classes? There are utility classes which only have static members. There are ordinary classes which have as few static members as possible. And each stays in the station in life to which it was born?

    Yes, ordinary classes can have static nested types and static factory methods, but other than that avoid anything static?
     
    Tim Holloway
    Saloon Keeper
    Posts: 21128
    131
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I have yet to come up with a hard and fast rule. Only that I know I'd better have good reason for making a class totally static. Because, as I said, it frequently ends up needing instantiations.
     
    William Codice
    Greenhorn
    Posts: 10
    Linux Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hi ,

    I try to be a little more clear . I drew this kind of flow diagram : https://ibb.co/SPHxppj

    The code waits for events and prints the received message or executes a command. Database writes every data after every command is executed.
    In the meantime the Task writes a few data at fixed rate

    I'm wondering if the class that handles events and the database have to be Static
     
    Sheriff
    Posts: 6266
    167
    Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
    • Likes 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Let's pull the image out of that link. Many people are reluctant to click a link in a post.

    I did this by right-clicking on the image in the link, selecting Copy image link, and putting that in an Img tag.  You can too, next time.
     
    William Codice
    Greenhorn
    Posts: 10
    Linux Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Knute Snortum wrote:Let's pull the image out of that link. Many people are reluctant to click a link in a post.

    ok

    I converted event handler class and database class to static. It seems to work
     
    Junilu Lacar
    Marshal
    Posts: 14039
    234
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    William Codice wrote:I converted event handler class and database class to static. It seems to work


    Until it doesn't. I'd be interested to see the actual code you write and the context you use them in. That will give people a better idea of the kind of problems you might be making for yourself with statics. Event handlers, especially, are normally object instances, not statics. If your static class maintains state, then you're setting yourself up for a world of hurt. Same issue with database classes, especially in a concurrent environment, like in a web application that services multiple concurrent requests.
     
    William Codice
    Greenhorn
    Posts: 10
    Linux Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks for your interest. Since the code is a little long ,  I'll try to be tidy,
    There is the 90% of the code because there are a few class not related


    Class Discord+Event


     
    William Codice
    Greenhorn
    Posts: 10
    Linux Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Class dbase = Database



    Class commandFactory+ interface



     
    Junilu Lacar
    Marshal
    Posts: 14039
    234
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Yeah, just a quick look at that Dbase class would give me concern since it has shared state in conn. In a concurrent environment where one thread might be calling connectionTo and another thread might be calling close(), who wins? Do you really want to risk close() getting called immediately after some other thread just called connectionTo()?
     
    Master Rancher
    Posts: 259
    12
    IntelliJ IDE Spring Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Just a side question for the more experienced developers among us: when you see a large code set, how do you start reading it? Top to bottom, or do you first check for specific or common red flags before reading in more detail?

    I'd be interested to know...  Whenever I (i.e. a beginner) see such a large code snippet, I feel lost. Not knowing where to start or what to look out for first...
     
    Junilu Lacar
    Marshal
    Posts: 14039
    234
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It's hard to say exactly but I have a sense that it involves some heuristics and a sensitivy to code smells honed through years of looking at messy code and dealing with design problems.

    In this case, I had warned against some common problems that statics tend to present, namely shared state is the enemy of concurrency. So I quickly scanned the code to see if there were any static or instance fields that had unsynchronized access and sure enough there were.
     
    Tim Holloway
    Saloon Keeper
    Posts: 21128
    131
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Brecht Geeraerts wrote:Just a side question for the more experienced developers among us: when you see a large code set, how do you start reading it? Top to bottom, or do you first check for specific or common red flags before reading in more detail?

    I'd be interested to know...  Whenever I (i.e. a beginner) see such a large code snippet, I feel lost. Not knowing where to start or what to look out for first...



    Well, on the Ranch, my eyes generally glaze over, I superficially scan and then volunteer answers based on mistaken assumptions.

    When I'm being paid to deal with stuff like this, I'll often simply print it out. Because reading stuff that can't fit on a single screen is distracting, confusing, and strains my vision.

    Which is why I have margin display on my text editor turned on and try to make sure that my own code/comments don't extend beyond 65 columns. Why 65? Legacy of working with punched cards. Plus it's about all you can print on a line when using a comfortably large typeface to A4/US letter sized printouts.

    Then I'll grab a highlighting pen and start marking critical stuff. Really serious stuff requires a pink highlighter. Why pink? Why not?

    As a side note, Java is not COBOL. OOP languages shouldn't have large blocks of code. If a single method cannot fit on a single monitor screen, it's probably trying to do too much. And even if you have multiple methods in your example when posting to the Ranch, please try to distill them down to the parts of actual interest. The incidental stuff might be critical in real life, but it makes it harder to understand both for us and the person posting.

     
    Junilu Lacar
    Marshal
    Posts: 14039
    234
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Here's another potential problem that jumped out at me because I'm familiar with the pattern: The way the Discord class implements lazy initialization of its singleton instance. See double-check locking is broken
     
    William Codice
    Greenhorn
    Posts: 10
    Linux Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The db will be always open with only one client
    maybe I've complicated the code with that timer

    but other than that...the Double-checked locking theory led me to read interesting stuff about singleton and the anti-pattern ...I keep reading !
    I'll even try to improve the methods code


     
    Campbell Ritchie
    Marshal
    Posts: 65782
    250
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Kindly don't edit old posts after they have been replied to.
     
    William Codice
    Greenhorn
    Posts: 10
    Linux Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:Kindly don't edit old posts after they have been replied to.



    ok

    Thanks I tried to learn some stuff about singleton,but I have a question

    From what I understand the singleton pattern has to ensure that only instance of the class gets created and it has to provide an method to get instance : getInstance()
    The only instance created ensure a kind of global access to custom static method. Static are the methods and not the classes like Mr.Tim said , but we can declare the class final.
    However there is a catch in multi-thread world :
    Because we have a single instance and many requests to access to static method we have to synchronized it by synchronized().
    Unfortunately synchronized() "deviate" the coming thread and locks the current thread, no others thread are allowed to enter.
    There is an improved solution, Double checked locking.


    It synchronizes the thread only when the instances gets created the first time,  that is when _singleton is null.
    for example:

    1) Thread1 gets in the getInstance() and sees a null instance. It goes in the syncronized() and gets the lock.
    2) Thread2 calls getInstance() but it cant get in because of Thread1 locked.
    3) Thread1 gets unlocked and create a new instance.
    4) Thread2 retry , gets in the syncronized() but returns immediately because instances is not null.
    5) No Thread will syncronized from now on

    Question:
    When Thread2 ( row n° 2 ) exit from getInstance because of Thread1 locked , Does It get a instance null ??
    I'm sorry for poor english
    Thanks
     
    Campbell Ritchie
    Marshal
    Posts: 65782
    250
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    What makes you think that double checked locking is an improvement? Double checked locking doesn't even work for all versions of Java®, though the versions with that problem are old enough to be obsolete.
    If you want to create a class to be a singleton, this is what you do:-Your example isn't a singleton because other code can call its default constructor. That is why you need a private constructor (see Java® Language Specification =JLS). And of course, the best way to create a singleton is like this:-You can add constructors, fields, methods, etc.
     
    William Codice
    Greenhorn
    Posts: 10
    Linux Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I have but I forgot to add in the post


    I read that double check was broken before java 5.
    but nevermind , let me study your code , thanks
     
    William Codice
    Greenhorn
    Posts: 10
    Linux Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:What makes you think that double checked locking is an improvement? Double checked locking doesn't even work for all versions of Java®, though the versions with that problem are old enough to be obsolete.
    If you want to create a class to be a singleton, this is what you do:
    ...

    Thanks , Solved

     
    Danger, 10,000 volts, very electic .... tiny ad:
    Java file APIs (DOC, XLS, PDF, and many more)
    https://products.aspose.com/total/java
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!