Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice in synchronized methods in jsf and java

Tags:

java

ajax

jsf

I have a JSF application where the users create some files. The problem is, they must upload them and download the confirmation messages too and the process of uploading/downloading is exclusive, only one user at the time, because the authentication requires a technical user/password. My question is, how can I make the waiting process transparent for the user, a kind of protocol, for example:

  • waiting to get the connection
  • authentication
  • upload file
  • download confirmation file
  • done
like image 465
claudia b Avatar asked Oct 23 '22 23:10

claudia b


1 Answers

Use a single thread executor.

@ManagedBean
@ApplicationScoped
public class FileManager {

    private ExecutorService executor;

    @PostConstruct
    public void init() {
        executor = Executors.newSingleThreadExecutor();
    }

    public Result process(Task task) throws InterruptedException, ExecutionException {
        return executor.submit(task).get();
    }

    @PreDestroy
    public void destroy() {
        executor.shutdownNow();
    }

} 

Where Result is just your javabean object containing the desired result and Task look like this:

public class Task implements Callable<Result> {

    private Data data;

    public Task(Data data) {
        this.data = data;
    }

    @Override
    public Result call() throws Exception {
        Result result = process(data); // Do your upload/download/auth job here.
        return result;
    }

}

Data is just your javabean object containing the input data (uploaded file?). Finally invoke it from in your managed bean as follows:

@ManagedBean
@RequestScoped
public class Bean {

    @ManagedProperty("#{fileManager}")
    private FileManager fileManager;

    public void submit() {
        try {
            Data data = prepareItSomehow();
            Result result = fileManager.process(new Task(data));
            // Now do your job with result.
        }
        catch (Exception e) {
            // Handle
        }
    }

    // ...
}

This way all tasks will be processed by a single thead in the first in - first out order.

If your container supports EJB, then there are other ways.

like image 192
BalusC Avatar answered Oct 27 '22 09:10

BalusC