0

Good night, I m not all secure on the execution of the fileupload Primefaces.

The uploading execution occurs normally, but I would like to have a counter that control's

the received files. The problem is that sending files go by so fast by this method that he

appears to be running in parallel. My question is whether this behavior is normal while sending files.

If it is not, where may be the error. If it is normal what can i do to make the counter really take the right value?

I'm using the scope of the "bean" type of view, but when im trying to run the session the problem also occurs depending on the file size.

If my files are very small, the execution is very fast and I cant follow the counter.

If I clean the code the execution usually occurs no matter the size of the files.

@ManagedBean (Name = "bean") 
@ViewScoped 
public class BeanUpload { 

private int counter;

@PostConstruct 
public void init () { 
    counter = 0; 
} 
public void fileUploadAction (FileUploadEvent event) {
    counter = counter + 1; 
    System.out.println ("COUNTER EX:" + counter); 
}

}

xhtml:

<h:form prependId="false" id="form1" name="form1" enctype="multipart/form-data">
<p:outputPanel id="divUpload" style="padding-bottom: 8px;">
    <p:fileUpload id="upload"  
        mode="advanced"  fileUploadListener="#{bean.fileUploadAction}"
        multiple="true"  sizeLimit="10485760" cancelLabel="Cancelar" fileLimit="4" allowTypes="/(\.|\/)(gif|jpe?g|png|pdf|odt|doc|docx|xls|xlsx|cvs|txt|xml)$/" >
     </p:fileUpload>        
</p:outputPanel>

The result on the console for 3 files is:

COUNTER EX: 1 
COUNTER EX: 1 
COUNTER EX: 1 

If I run the code in debug mode on the console this is the result:

COUNTER EX: 1 
COUNTER EX: 2 
COUNTER EX: 3 
Lobo
  • 9
  • 1

1 Answers1

2

You should use java.util.concurrent.atomic.AtomicInteger for thread correctness.

private AtomicInteger counter;
...
System.out.println ("COUNTER EX:" + counter.incrementAndGet()); 

This could also be a symptom of another thread safety problem - p:fileUpload multiple violates JSF's concurrency requirements and may trigger unexpected behavior (e.g. construct multiple BeanUpload instances). See this answer.

Community
  • 1
  • 1
Vsevolod Golovanov
  • 4,068
  • 3
  • 31
  • 65