Categories
discuss

Program not terminating after loop completion

In the following scenario, the boolean ‘done’ gets set to true which should end the program. Instead the program just keeps going on even though the while(!done) is no longer a valid scenario thus it should have halted. Now if I were to add in a Thread sleep even with zero sleep time, the program terminates as expected. Why is that?

public class Sample {

    private static boolean done;

    public static void main(String[] args) throws InterruptedException {
        done = false;
        new Thread(() -> {
            System.out.println("Running...");
            int count = 0;
            while (!done) {
                count++;
                try {
                    Thread.sleep(0); // program only ends if I add this line. 
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Thread.sleep(2000);

        done = true; // this is set to true after 2 seconds so program should end.
        System.out.println("Done!"); // this gets printed after 2 seconds
    }

}

EDIT: I am looking to understand why the above needs Thread.sleep(0) to terminate. I do not want to use volatile keyword unless it is an absolute must and I do understand that would work by exposing my value to all threads which is not my intention to expose.

Answer

Each thread have a different cached version of done created for performance, your counter thread is too busy making the calculations for count that it doesnt give a chance to reload done.

volatile ensures that any read/write is done on the main memory, always update the cpu cache copy.

Thread.sleep always pause the current thread, so even if 0 your counter thread is interrupted by some time <1ms, that is enough time for the thread to be adviced of done variable change.

Categories
discuss

Paths.get vs Path.of

As far as I can tell, Paths.get and Path.of seem to do exactly the same thing, turning one or more strings into a Path object; the documentation https://docs.oracle.com/javase/8/docs/api/java/nio/file/Paths.html#get-java.lang.String-java.lang.String…- and https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/file/Path.html#of(java.lang.String,java.lang.String…) use the same wording. Are they in fact identical?

Path.of was introduced later. Conjecture: it was introduced for the sake of a consistent Foo.of style. In that case, it would be considered preferable on consistency/aesthetic grounds?

Answer

Indeed, Path.of was later introduced.

Conjecture: it was introduced for the sake of a consistent Foo.of style.

From the mailing list archive, this method was once called Path.get:

The main changes in are in Path and Paths in java.nio.file.

This patch copies the Paths.get() methods to static methods in Path.get() and modifies the former to call the latter respective methods. The Path specification is slightly cleaned up not to refer to Paths nor itself, e.g., “(see Path).” @implSpec annotations are added to Paths to indicate that the methods simply call their counterparts in Path.

This was later changed when Brian Goetz suggested it to be consistent with Foo.of:

Separately, Brian Goetz suggested off-list that it would be more
consistent if these factory methods were named “of” so I assume the
webrev will be updated to see how that looks.

Now to your last question: “In that case, it would be considered preferable on consistency/aesthetic grounds?”
In the initial mail Brian Burkhalter said that he updated all references to the new method in Path:

All source files in java.base are modified to change Paths.get() to Path.get() and to remove the import for Paths. …

So I would therefore conclude that Path.of is indeed preferable to Paths.get.
Indeed, if you look at the Javadoc for Paths for Java 13 you will find this note:

API Note:
It is recommended to obtain a Path via the Path.of methods instead of via the get methods defined in this class as this class may be deprecated in a future release.

Categories
discuss

You Don’t Know JS: Async and Performance – cooperative concurrency?

Kyle example is about chunking data (when is so big) by asynchronous events and make events interleave in the event loop queue, that part i couldn’t get:

The example from book:

var res = [];
// `response(..)` receives array of results from the Ajax call
function response(data) {

   var chunk = data.splice( 0, 1000 );

   res = res.concat(

    chunk.map( function(val){
      return val * 2;
    } )
  );

  if (data.length > 0) {

    setTimeout( function(){
        response( data );
    }, 0 );
  }
}
// ajax(..) is some arbitrary Ajax function given by a library
ajax( "http://some.url.1", response );
ajax( "http://some.url.2", response );

I could not get that part, my mind can not accept that this could make code perform better, wouldn’t that cause data from two arrays to interleave, or i just don’t understand how event loop work??

Answer

It appears that you are correct that there is a potential for misordering of data with multiple ajax calls (and it was very astute of you to notice, +1), with the code posted you could get:

  1. ajax call 1 starts
  2. ajax call 1 finishes
  3. append the first 1000 elements from call 1
  4. ajax call 2 starts
  5. append the next 1000 elements from call 1
  6. ajax call 2 finishes
  7. append the first 1000 elements from call 2
  8. append the next 1000 elements from call 1

As for the performance aspect of the question, remember that ‘performance’ isn’t just one thing. If by performance you mean ‘how long does this block of code take to run’ then chunking will lead to worse performance. But this is frontend. ‘Performance’ is really about user experience, and your Javascript code runs on the main thread. If you have a 10 second operation then your UI is unresponsive for 10 seconds. If you chunk it then the user can still interact with the page while it’s running, even if it takes a little longer to complete.

Categories
discuss

How to test if a component is rendered with the right props when using react-testing-library?

I have some components that are rendering another component (FetchNextPageButton) that is already tested in isolation, like these ones:

const News = () => (
  <div>
    <h1>News</h1>
    ...
    <FetchNextPageButton query={NEWS_QUERY} path="viewer.news" />
  </div>
)

const Jobs = () => (
  <div>
    <h1>Jobs</h1>
    ...
    <FetchNextPageButton query={JOBS_QUERY} path="viewer.jobs" />
  </div>
)

const Posts = () => (
  <div>
    <h1>Posts</h1>
    ...
    <FetchNextPageButton query={POSTS_QUERY} path="viewer.posts" />
  </div>
)

The thing is that I’d not like having to add tests on each of these components for a functionality that is already tested somewhere else, so I think that should be enough just to test that the component is rendered and that I’m passing the right props to it.

I’d have been able to test this easily with Enzyme with something like this:

expect(wrapper.find('FetchNextPageButton').props()).toMatchObject({
  query: NEWS_QUERY,
  path: "viewer.news"
})

So I’m wondering what’s the best approach to test it by using React testing library instead.

Answer

This is the approach that Kent C. Dodds (the creator of RTL) shared with me after discussing it with him:

import FetchNextPageButton from 'FetchNextPageButton'

jest.mock('FetchNextPageButton', () => {
  return jest.fn(() => null)
})

// ... in your test
expect(FetchNextPageButton).toHaveBeenCalledWith(props, context)
Categories
discuss

How to upload file into Wasabi bucket with s3 api with node.js?

I implemented uploading file in Amazon s3 bucket like below and it works fine:

  const S3 = require('aws-sdk/clients/s3');
  const AWS = require('aws-sdk');

  const accessKeyId = 'AKIAYVXDX*******';
  const secretAccessKey = 'gxZpdSDnOfpM*****************';

  const s3 = new S3({
    region: 'us-east-1',
    accessKeyId,
    secretAccessKey
  });

  s3.putObject({
      Body: 'Hello World',
      Bucket: "dev-amazon",
      Key: 'hello.txt'
    }
    , (err, data) => {
      if (err) {
         console.log(err);
      }
    });

And I need to implement uploading file in Wasabi bucket.

I tried like below:

  const S3 = require('aws-sdk/clients/s3');
  const AWS = require('aws-sdk');
  const wasabiEndpoint = new AWS.Endpoint('s3.wasabisys.com');

  const accessKeyId = 'PEIL4DYOY*******';
  const secretAccessKey = 'D4jIz3tjJw*****************';

  const s3 = new S3({
    endpoint: wasabiEndpoint,
    region: 'us-east-2',
    accessKeyId,
    secretAccessKey
  });

  s3.putObject({
      Body: 'Hello World',
      Bucket: "dev-wasabi",
      Key: 'hello.txt'
    }
    , (err, data) => {
      if (err) {
         console.log(err);
      }
    });

And the result of `console.log(err) is:

err {“message”:”The request signature we calculated does not match the signature you provided. Check your key and signing method.”,”code”:”SignatureDoesNotMatch”,”region”:null,”time”:”2019-10-30T09:39:19.072Z”,”requestId”:null,”statusCode”:403,”retryable”:false,”retryDelay”:64.72166771381391}

Console error in devtools:

PUT https://dev-wasabi.s3.us-east-2.wasabisys.com/5efa9b286821fab7df3ece8dc3d6687ed32 403 (Forbidden)

What is wrong in my codes?

Answer

I found the reason of this issue myself.

wasabiEndpoint was wrong. It should be

  const wasabiEndpoint = new AWS.Endpoint('s3.us-east-2.wasabisys.com ');

According to docs, service URLs should be different based on regions.

Wasabi US East 1 (N. Virginia): s3.wasabisys.com or s3.us-east-1.wasabisys.com

Wasabi US East 2 (N. Virginia): s3.us-east-2.wasabisys.com

Wasabi US West 1 (Oregon): s3.us-west-1.wasabisys.com

Wasabi EU Central 1 (Amsterdam): s3.eu-central-1.wasabisys.com

I will be very grateful if this helps someone. 🙂

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..