Instantiate an object throughout the life cycle of the Java application

Asked

Viewed 140 times

3

I have an application here in Java that uses the Amazon SDK to send images to a Bucket S3.

To do this I use threads, basically it is modeled as follows:

The class Main has a thread list and each item in the list is sent to a Executor class and this calls a class Callable that downloads an image and returns the image information to the image uploader.

The problem that every time I send the image I have to connect to Bucket. Look:

BasicAWSCredentials credentials = new BasicAWSCredentials("Usuario", "Senha");
AmazonS3 s3client = AmazonS3ClientBuilder.standard()
    .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .withRegion(Regions.US_EAST_1).build();

Can anyone tell me a way to instantiate these connecting objects in the Main for when I arrive at the Executor when sending I am already connected?

  • You are running the local application or is it an EC2 instance?

  • The application I spin from my own machine.

  • 1

    Configure your credentials on the machine, hence you do not need to be informing user and password hard coded. And if you’re going to upload your application to an EC2 setting, just give S3 access permission via IAM.

  • But even so I will have to connect every time. What I need is to perform this connect operation only once.

  • Ah understood... Just you pass the instance of the Amazons3 class to your executing class. Define a constructor in the executing class that takes an argument of type Amazons3, likely to solve.

  • You can’t use a Singleton? (although I think keeping a connection open is a bad idea)

  • @Igorventurelli It can! There is no "connection" open, it is just an Http Request without Keep Alive.

  • User and password are fixed?

  • They are fixed, thanks for the reply friend, soon I will try here!

Show 4 more comments

2 answers

2


First, encapsulate the creation of the AmazonS3:

private static AmazonS3 criarClient(String usuario, String senha) {
    BasicAWSCredentials credentials = new BasicAWSCredentials(usuario, senha);

    return AmazonS3ClientBuilder
        .standard()
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .withRegion(Regions.US_EAST_1)
        .build();
}

And then, if the user and password are fixed, you can do this:

private static final AmazonS3 CLIENT = criarClient("Usuário", "Senha");

The object AmazonS3 is thread-safe and unchanging. So, if the user and password are fixed, you can safely put it into a static variable only once when your class in question is being loaded, even if there are multiple threads involved

If the user and password are not fixed, just use the method criarClient once for each login/password you will use, even if instances will be used concurrently by multiple threads.

1

Just to clarify a few points that were a little confusing:

There is no "being connected to Bucket", what aws sdk is doing is taking your credentials to sign the request, you are working with http requests (no Keep Alive).

A simple example:

public class AmazonS3Worker implements Runnable {

    private AmazonS3 s3;

    public AmazonS3Worker(AmazonS3 s3) {
        this.s3 = s3;
    }

    @Override
    public void run() {

        //download com s3.getObject

    }

}

and on Main:

public static void main(String [] args) {

    BasicAWSCredentials credentials = new BasicAWSCredentials("Usuario", "Senha");
    AmazonS3 s3client = AmazonS3ClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
            .withRegion(Regions.US_EAST_1).build();

    ExecutorService executor = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 10; i++) {
        Runnable worker = new AmazonS3Worker(s3client);
        executor.execute(worker);
    }

    executor.shutdown();
    while(!executor.isTerminated()) {}
    System.out.println("Done!");

}
  • So Tom, actually my classes are structured in a slightly different way, because in the Main class I call a class that implements Runnable, so I would have to pass to it the already instantiated object.... But thanks for the tip!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.