Win a copy of Classic Computer Science Problems in Swift this week in the iOS forum!

Sresh Rangi

Ranch Hand
+ Follow
since Nov 28, 2012
Cows and Likes
Total received
In last 30 days
Total given
Total received
Received in last 30 days
Total given
Given in last 30 days
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Sresh Rangi

You don't need to leak a reference to this to get a partially constructed object. That is only true in single-threaded programs.

If you create an object, and then pass it to another thread, then there aren't any happens-before relationships between the constructor and the get method and you can see the uninitialized value.

But because you've started the thread after calling the constructor, then there is a happens-before relationship. Because a call to start() on a thread happens-before any actions in the started thread. See 17.4.5 in the JLS
2 months ago
I found a library called Cactoos which they've created based on some object-orientated principles:

  • No null
  • No code in constructors
  • No getters and setters
  • No mutable objects
  • No static methods, not even private ones
  • No instanceof, type casting, or reflection
  • No implementation inheritance
  • No public methods without @Override
  • No statements in test methods except assertThat

  • As an example, they sort a file like:

    They claim that their code is more object-orientated, but it doesn't seem better than alternatives like Guava to me. What do you think of the design of this? Some of the code they produce does look like they're heading towards a functional programming style so maybe they'd be better embracing that instead.
    Is anyone using the hotswap feature in Java to reload classes? I found you can modify the source code in eclipse while a program is running and the changes will appear in the program. This does only only changes to method bodies though but tools like JRebel and DCEVM are extending this.

    This seems to be useful in GUI programs as it saves restarting the program and finding the dialog you were working on, or inputting values again. It's more convenient to change individual ui controls interactively and see the changes as you're writing them. I wish I tried this earlier as it would have saved time restarting programs and going though repetitive ui actions.

    What are the best ways to take advantage of this? One thing I found was that you'd need to calculate values each time they're used instead of once at the beginning. So instead of:

    you can use:

    You can also have a button to do a partial reinitialization of the state of the program. In case you want to change the initial values as the program is running.
    1 year ago
    A problem with these benchmarks is that the effect of JIT compilation and GC collection can affect the results. Here, it's the one that runs first that's slower.


    I get:

    and with:

    I get:

    I tried this JMH benchmark:

    With results (higher is better):

    So adding to the end of an ArrayList is faster.

    ArrayLists do need to be resized as elements are added, but the time between each resize increases exponentially as the size increases. This gives a constant time per element added.

    Also, the elements in an ArrayList are stored in an array which keeps all the elements together in RAM. A resize is just copying a contiguous block of memory from one location to another, which computers do all the time.

    With a LinkedList, you need to update the previous pointer, and the current pointer, and allocate a new object for the new node. Which is more of an overhead per item.

    Stephan van Hulst wrote:+++ is ambiguous because it might mean + ++ or it might mean ++ +. My guess is that the Java lexer tokenizes characters greedily, so in these cases it will always pick the option where the token with the most characters comes first.

    I think this is right. From the JLS:

    The longest possible translation is used at each step, even if the result does not ultimately make a correct program while another lexical translation would.

    Thus, the input characters a--b are tokenized (ยง3.5) as a, --, b, which is not part of any grammatically correct program, even though the tokenization a, -, -, b could be part of a grammatically correct program.

    The '++' token is given in section 3.12 without any regard to the structure of the expression or whether it's a prefix or postfix operator.

    Chapter 3 describes the lexical grammar which is what groups the plus characters together, The precedence is part of the syntactic grammar which comes later.
    2 years ago
    I'd start by replacing the if-else structures with early returns, and introduce some boolean variables for the conditions. This makes it see any pattern, and rearrange the code. I've replaced Date with LocalDate (from Java 8 or JodaTime). They remove the need for the util methods and remove ambiguity of whether it contains a time or not.

    Then you can see that if you move "WARNING" earlier, then some of the later conditions become redundant, so you can simplify the logic to:

    It doesn't look like the default "NEW" value can be returned. I think it would be misleading to return this value by default so I've replaced it with null. You could remove the last condition and return "HIGHLY_PROBLEMATIC" instead but I like the explicit condition.
    2 years ago
    This can be done with the newer CompletableFuture class. Libraries like guava have similar classes if Java 8 is not available. Create a CompletableFuture inside the checkout method:
    Call inside the callback, and outside it to get its value.
    In your example, toString() isn't being called on the array, it's being called on the first element within the array. Because printf takes vararg parameters, the last parameter is interpreted as an array containing the remaining parameters. So:

    is really the same as:

    See if you can explain the results of:

    Maybe replace new Object() with string literals to see what's happening.
    There is a lot of misinformation of cross site scripting out there. Be careful of the sources you use. The first place I would check is:

    For cross site scripting, you should be escaping untrusted data when outputting it on a page. The tag libraries for web frameworks should have a way of doing this for you.

    A blacklist approach like you're using is not recommended. It always leaves many holes in the filtering. For example, you're escaping "eval()" but not "eval ()". See for how these filters can be bypassed.

    Luckily, this is a solved problem. If you need escaping, use premade, fully tested libraries like:

    Replacing input parameters has a few problems. One is that you are removing or corrupting valid user input as well as malicious input. What if the user wants to search for "script"? Another is that it doesn't take output context into account. Data that is safe for attribute values might not be safe for css styles, or javascript contents. This is why these encoder libraries focus on escaping output rather than input, and they have multiple escape methods depending on context.
    3 years ago
    I've been working on some web applications that make heavy use of printStackTrace(), or System.err.println(...) for error messages.

    Is this common in real programs? I've found it difficult to work with because all messages go to the same file without any date/time or usernames so it's difficult to tell which messages go together or where they come from. These files also fill up with junk/debugging output which make it difficult to find important information in them.

    There seems to be many different logging libraries for Java. Would SLF4J work well? It seems to have compatibility with some of the other libraries so it looks quite flexible. I would probably use Logback or Log4J along with it.

    Does anyone use the Mapped Diagnostic Context features of these libraries? Adding username and ip addresses to the messages would be useful. Anything else?

    Also, how would you view the log files? Do you log to a database, or use any specific programs?
    3 years ago
    It's also common to create a new session when the user is authenticated. This is needed to prevent some session hijacking attacks.

    See OWASP Session Management Cheat Sheet:

    The session ID must be renewed or regenerated by the web application after any privilege level change within the associated user session. The most common scenario where the session ID regeneration is mandatory is during the authentication process, as the privilege level of the user changes from the unauthenticated (or anonymous) state to the authenticated state.

    3 years ago

    fred rosenberger wrote:I swear someone once told me about a custom boolean class written for the company's application that would return "true", "false", or "file not found".

    A classic:

    What is Truth?
    4 years ago
    The [[prototype]] notation is from the ECMAScript specification. It is an internal property that exists on every object. The constructor's prototype property is used to set the initial value of [[prototype]]. When the object's properties are accessed, then JS follows the chain of [[prototype]]s until it finds an object that has that property.

    It is accessible in browser dependent ways, for example Firefox uses a __proto__ property. See __proto__

    Although this should never be manipulated in real code, it can be useful for seeing how objects work in JavaScript.