Found this interesting class AtomicInteger that allows you to access primitives in a highly concurrent environment. I ran into an issue when I had to implement a throttling filter to allow only certain no of request in the app for a particular functionality to guarantee a certain level of QOS, my earlier code was
public class BackupThrottlingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
activeBackupRequests ++;
if(activeBackupRequests > 50) {
BackupFileUploadServlet.sendServiceUnavailableResponse((HttpServletResponse) response);
return;
}
chain.doFilter(request, response);
}
finally {
activeBackupRequests--;
}
}
private static int activeBackupRequests;
}
Ran into an issue with this as its not synchronized so I had an option to use volatile or synchronized ,but synchronized is a killer as it would block but then I read about the new AtomicInteger class that allows you to abstract all this and allow highly concurrent operations on primitives
public class BackupThrottlingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
activeBackupRequests.incrementAndGet();
if (activeBackupRequests.get() > 50) {
BackupFileUploadServlet.sendServiceUnavailableResponse((HttpServletResponse) response);
return;
}
chain.doFilter(request, response);
} finally {
activeBackupRequests.decrementAndGet();
}
}
private static AtomicInteger activeBackupRequests = new AtomicInteger(0);
}
public class BackupThrottlingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
activeBackupRequests ++;
if(activeBackupRequests > 50) {
BackupFileUploadServlet.sendServiceUnavailableResponse((HttpServletResponse) response);
return;
}
chain.doFilter(request, response);
}
finally {
activeBackupRequests--;
}
}
private static int activeBackupRequests;
}
Ran into an issue with this as its not synchronized so I had an option to use volatile or synchronized ,but synchronized is a killer as it would block but then I read about the new AtomicInteger class that allows you to abstract all this and allow highly concurrent operations on primitives
public class BackupThrottlingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
activeBackupRequests.incrementAndGet();
if (activeBackupRequests.get() > 50) {
BackupFileUploadServlet.sendServiceUnavailableResponse((HttpServletResponse) response);
return;
}
chain.doFilter(request, response);
} finally {
activeBackupRequests.decrementAndGet();
}
}
private static AtomicInteger activeBackupRequests = new AtomicInteger(0);
}
Comments
Post a Comment